无法使用tkinter解除绑定功能 [英] Unable to unbind a function using tkinter
问题描述
我正在Python 3.5中使用Tkinter,但遇到一个奇怪的问题.
I am working with Tkinter in Python 3.5 and I encounter a weird problem.
我使用了 tkinterbook关于事件和绑定的方法来编写这种简单的代码例如:
I used the tkinterbook about events and bindings to write this simple example:
from tkinter import *
root = Tk()
frame = Frame(root, width=100, height=100)
def callback(event):
print("clicked at", event.x, event.y)
# frame.unbind("<Button-1>", callback)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()
它工作正常,但是如果我尝试取消绑定回调(只需取消注释该行),它将失败并显示以下错误:
It works fine, but if I try to unbind the callback (just uncomment the line), it fails with the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Delgan\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\Delgan\Desktop\Test\test.py", line 9, in callback
frame.unbind("<Button-1>", callback)
File "C:\Users\Delgan\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1105, in unbind
self.deletecommand(funcid)
File "C:\Users\Delgan\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 441, in deletecommand
self.tk.deletecommand(name)
TypeError: deletecommand() argument must be str, not function
目前尚不清楚,我不确定这是tkinter中的错误还是做错了事.
This is not clear, I am not sure if it is a bug in tkinter or if I am doing something wrong.
frame.unbind("<Button-1>")
正常工作,但我想删除此确切的回调而不是全局删除.
frame.unbind("<Button-1>")
works fine but I would like to remove this exact callback instead of a global remove.
推荐答案
unbind
的第二个参数是'funcid',而不是函数. help(root.unbind)
返回
The second argument to unbind
is a 'funcid', not a function. help(root.unbind)
returns
tkinter.Tk实例的
unbind(sequence, funcid=None)
方法. 对此事件SEQUENCE的此小部件取消绑定,用FUNCID标识的功能.
unbind(sequence, funcid=None)
method of tkinter.Tk instance. Unbind for this widget for event SEQUENCE the function identified with FUNCID.
许多tk函数返回tk对象ID,它们可以作为其他函数的参数,而bind是其中之一.
Many tk functions return tk object ids that can be arguments for other funtions, and bind is one of them.
>>> i = root.bind('<Button-1>', int)
>>> i
'1733092354312int'
>>> root.unbind('<Button-1>', i) # Specific binding removed.
help(root.bind)
的输出中包含以下内容:绑定将返回一个标识符,以允许删除绑定的函数而无需解除绑定而不会发生内存泄漏."
Buried in the output from help(root.bind)
is this: "Bind will return an identifier to allow deletion of the bound function with unbind without memory leak."
这篇关于无法使用tkinter解除绑定功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!