Unable to unbind a function using tkinter

僤鯓⒐⒋嵵緔 提交于 2019-12-12 12:33:40

问题


I am working with Tkinter in Python 3.5 and I encounter a weird problem.

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

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>") works fine but I would like to remove this exact callback instead of a global remove.


回答1:


The second argument to unbind is a 'funcid', not a function. help(root.unbind) returns

unbind(sequence, funcid=None) method of tkinter.Tk instance. Unbind for this widget for event SEQUENCE the function identified with FUNCID.

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.

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."



来源:https://stackoverflow.com/questions/37902503/unable-to-unbind-a-function-using-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!