I'm trying to unbind/disable key once it's clicked, and resume its function after 2s. But I can't figure out the code for the unbinding. The bind is on window. Here's the code that I tried so far:
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"))
Further, how can I re-enable the key after 2s?
Thank you so much!
self.master.unbind('a', self.choiceA)
does not work because the second argument you gave is the callback you want to unbind instead of the id returned when the binding was made.
In order to delay the re-binding, you need to use the .after(delay, callback)
method where delay
is in ms and callback
is a function that does not take any argument.
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()
Remark: since you use a class, my bind_id
global variable will be an attribute for you (self.bind_id
).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments