python unbinding/disable 点击后按键绑定,稍后恢复

python unbinding/disable key binding after click and resume it later

我正在尝试 unbind/disable 键一旦被点击,并在 2 秒后恢复其功能。但是我无法弄清楚解除绑定的代码。绑定在 window。这是我到目前为止尝试过的代码:

self.choiceA = self.master.bind('a', self.run1) #bind key "a" to run1
def run1(self, event=None):
    self.draw_confirmation_button1()
    self.master.unbind('a', self.choiceA) #try1: use "unbind", doesn't work

    self.choiceA.configure(state='disabled') #try2: use state='disabled', doesn't't work, I assume it only works for button
    self.master.after(2000, lambda:self.choiceA.configure(state="normal"))

另外,如何在2秒后重新启用密钥?

非常感谢!

self.master.unbind('a', self.choiceA) 不起作用,因为您提供的第二个参数是您要取消绑定的回调,而不是进行绑定时返回的 id。

为了延迟re-binding,你需要使用.after(delay, callback)方法,其中delay以ms为单位,callback是一个不带任何参数的函数参数。

import tkinter as tk

def callback(event):
    print("Disable binding for 2s")
    root.unbind("<a>", bind_id)
    root.after(2000, rebind)  # wait for 2000 ms and rebind key a

def rebind():
    global bind_id
    bind_id = root.bind("<a>", callback)
    print("Bindind on")


root = tk.Tk()
# store the binding id to be able to unbind it
bind_id = root.bind("<a>", callback)

root.mainloop()

备注:由于您使用了 class,我的 bind_id 全局变量将成为您的属性 (self.bind_id)。