我试图在点击后取消绑定/禁用密钥,并在2秒后恢复其功能。但我无法弄清楚解除绑定的代码。绑定在窗口上。这是我到目前为止尝试的代码:
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"))
此外,如何在2s后重新启用密钥?
非常感谢你!
答案 0 :(得分:0)
self.master.unbind('a', self.choiceA)
不起作用,因为您提供的第二个参数是要取消绑定的回调,而不是绑定时返回的id。
为了延迟重新绑定,您需要使用.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()
备注:由于您使用的是某个类,我的bind_id
全局变量将成为您的属性(self.bind_id
)。