我对 python 还是有些陌生,并且正在开发一个包含 GUI 的项目。我经常使用 Tkinter 和按钮,并且很好奇是否有一种方法可以使用绑定(bind)运行函数,因为我希望在按下时发生一件事,而在释放时发生另一件事。
s = str(x+1) + ":" + str(y+1)
img = ImageTk.PhotoImage(Image.open('button.png'))
b = Tkinter.Button(field_hid, image=img, borderwidth=0, highlightthickness=0, background='grey')
b.bind("<ButtonPress-1>", lambda s=s, button=b: location_down(event,s,button))
b.bind("<ButtonRelease-1>", lambda s=s, button=b: location_up(event,s,button))
b.img = img
b.pack()
b.grid(row=x, column=y)
我不明白我该怎么做,因为唯一可以传递给函数的是事件,但我的程序需要参数。
最佳答案
使用 bind 的唯一方法是让它调用一个函数。当您使用 lambda
时,您只是在创建一个匿名函数。您可以轻松地做到:
b.bind("<ButtonPress-1>", self.SomeOtherFunction)
lambda
在您想要将附加参数传递给函数时非常有用。与使用 command
选项时不同,通过绑定(bind),您可以获得一个包含大量有用信息的事件对象,因此您可能不需要传递任何其他信息。
例如,您可以这样做:
def OnPress(event):
print "widget %s was pressed" % event.widget
def OnRelease(event):
print "widget %s was released" % event.widget
b = Button(...)
b.bind("<ButtonPress-1>", OnPress)
b.bind("<ButtonRelease-1>", OnRelease)
有关绑定(bind)的详细介绍,请参阅 Events and Bindings在 effbot.org 上。
关于Python Button 绑定(bind)两个函数并使用绑定(bind)发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6286412/