无法使用 tkinter 解除绑定函数

Del*_*gan 4 python binding tkinter python-3.5

我正在 Python 3.5 中使用 Tkinter,但遇到了一个奇怪的问题。

我使用了关于事件和绑定tkinterbook来编写这个简单的例子:

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()
Run Code Online (Sandbox Code Playgroud)

它工作正常,但如果我尝试取消绑定回调(只是取消注释该行),它会失败并出现以下错误:

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()
Run Code Online (Sandbox Code Playgroud)

这不清楚,我不确定这是 tkinter 中的错误还是我做错了什么。

frame.unbind("<Button-1>") 工作正常,但我想删除这个确切的回调而不是全局删除。

Ter*_*edy 6

的第二个参数unbind是“funcid”,而不是函数。 help(root.unbind)返回

unbind(sequence, funcid=None)tkinter.Tk 实例的方法。为事件 SEQUENCE 取消绑定此小部件,使用 FUNCID 标识的函数。

许多 tk 函数返回可以作为其他函数参数的 tk 对象 ID,bind 就是其中之一。

>>> i = root.bind('<Button-1>', int)
>>> i
'1733092354312int'
>>> root.unbind('<Button-1>', i)  # Specific binding removed.
Run Code Online (Sandbox Code Playgroud)

隐藏在输出中的help(root.bind)是这样的:“绑定将返回一个标识符,以允许在没有内存泄漏的情况下使用 unbind 删除绑定函数。”

  • 我知道这会晚一些,但对于所有遇到此问题的未来人来说:如果您只想解除绑定此功能,请执行:´´´root.unbind("",&lt;id&gt;)´´´ 因为上面的示例将删除所有绑定给定的序列 (´´´'&lt;Button-1&gt;'´´´) 与函数 id 无关。 (2认同)