python tkinter binding: How to prevent double events
This requires one of Tkinter's little known quirks, i.e. you have to return "break" from a function. The program below rebinds the key to the "ignore()" function that returns "break". I don't understand how or why this is, and it is documented http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm and does work.
import sysif sys.version_info[0] < 3: import Tkinter as tk ## Python 2.xelse: import tkinter as tk ## Python 3.xclass App: def __init__(self, master): # Constructor self.master=master self.counter=0 # build GUI self.label = tk.Label(text="Press <space>", width=40) self.label.grid(row=1, column=1, sticky='w') # bind keys to buttons master.bind('<Key-space>', self.keyPressed) def ignore(self, event): print "ignore" return "break" def keyPressed(self, event): self.master.bind('<Key-space>', self.ignore) print("Step 1") self.counter = self.counter + 1 self.label["text"] = str(self.counter) self.master.after(3000, self.bindit) print("Step 2") def bindit(self): self.master.bind('<Key-space>', self.keyPressed) print("Step 3 = ready for more input")root = tk.Tk()root.option_add('*font', ('Arial', 11, 'bold'))# root.attributes("-toolwindow", 1)posX = root.winfo_screenwidth() - 500posY = 30root.geometry("+%d+%d" % (posX, posY))root.title("Bind tester")display = App(root)root.mainloop()
Probably the time.sleep method is messing with Tkinter mainloop.You should use the 'after' method from Tkinter module.
http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html
If you do not pass a callback argument, this method waits delay_ms milliseconds, as in the .sleep() function of the standard Python time module.
Check this post for an example: