删除和更改 tkinter 事件绑定 [英] Deleting and changing a tkinter event binding
问题描述
如何停止处理事件或切换为其调用的函数?
How do i stop an event from being processed or switch what function is called for it?
修订代码:
from Tkinter import *
class GUI:
def __init__(self,root):
Window = Frame(root)
self.DrawArea = Canvas(Window)
self.DrawArea.pack()
Window.pack()
self.DrawArea.bind("<Button 1>",self.starttracking)
def updatetracking(self,event):
print event.x,event.y
def finishtracking(self,event):
self.DrawArea.bind("<Button 1>",self.starttracking)
self.DrawArea.unbind("<Motion>")
def starttracking(self,event):
print event.x,event.y
self.DrawArea.bind("<Motion>",self.updatetracking)
self.DrawArea.bind("<Button 1>",self.finishtracking)
if __name__ == '__main__':
root = Tk()
App = GUI(root)
root.mainloop()
推荐答案
您只需再次使用该事件的新函数调用 bind()
即可.由于您没有使用第三个参数,add
,在 bind()
中,这只会覆盖已经存在的任何内容.默认情况下,此参数为 ''
但它也接受 "+"
,这将向该事件已触发的回调添加回调.
You can simply just call bind()
again with the new function for the event. Since you are not making use of the third parameter, add
, in bind()
this will just overwrite whatever is already there. By default this parameter is ''
but it also accepts "+"
, which will add a callback to the callbacks already triggered by that event.
如果您开始使用该可选参数,则您将需要使用 unbind()
函数来删除单个回调.当您调用 bind()
时,会返回一个 funcid
.您可以将此 funcid
作为第二个参数传递给 unbind()
.
If you start using that optional argument however you will need to use the unbind()
function to remove individual callbacks. When you call bind()
a funcid
is returned. You can pass this funcid
as the second parameter to unbind()
.
示例:
self.btn_funcid = self.DrawArea.bind("<Button 1>", self.my_button_callback, "+")
# Then some time later, to remove just the 'my_button_callback':
self.DrawArea.unbind("<Button 1>", self.btn_funcid)
# But if you want to remove all of the callbacks for the event:
self.DrawArea.unbind("<Button 1>")
这篇关于删除和更改 tkinter 事件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!