如何在完成工作后删除键绑定

How to remove a keybind after it has done its job

我创建了一个快捷键,激活后想删除它。我该怎么做?

我已经在我的代码中试过了:

def testing(event):
    print("Hello!")

root.bind_all('<Key>', testing)
root.deletecommand('<Key>', testing)

但是,这不起作用,因为 Python 显示一条错误消息,指出 deletecommand() takes 2 positional arguments but 3 were given,而我只给出了两个参数。我也试过 root.delete('<Key>', testing),但这也失败了。

from tkinter import *

def testing(event):
    print("Hello!")

root.bind_all('<Key>', testing)
root.deletecommand('<Key>', testing)

root.pack()
root.mainloop()

我希望程序在完成它的工作后能删除键绑定。但是,Python 显示了一条错误消息,如前所述。我该如何解决这个问题?

试试这个

from tkinter import *
root = Tk()


def testing(event):
    print("Hello!")
    root.unbind_all('<Key>')


root.bind_all('<Key>', testing)
root.mainloop()

要取消绑定所有小部件,请使用函数 .unbind_all('<Key>')