Created
October 13, 2015 17:32
-
-
Save vtsatskin/8e3c0c636339b2228138 to your computer and use it in GitHub Desktop.
Listening to KeyPress and KeyRelease with Tkinter with debouncing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Tkinter as tkinter | |
tk = tkinter.Tk() | |
has_prev_key_release = None | |
''' | |
When holding a key down, multiple key press and key release events are fired in | |
succession. Debouncing is implemented in order to squash these repeated events | |
and know when the "real" KeyRelease and KeyPress events happen. | |
''' | |
def on_key_release(event): | |
global has_prev_key_release | |
has_prev_key_release = None | |
print "on_key_release", repr(event.char) | |
def on_key_press(event): | |
print "on_key_press", repr(event.char) | |
def on_key_release_repeat(event): | |
global has_prev_key_release | |
has_prev_key_release = tk.after_idle(on_key_release, event) | |
print "on_key_release_repeat", repr(event.char) | |
def on_key_press_repeat(event): | |
global has_prev_key_release | |
if has_prev_key_release: | |
tk.after_cancel(has_prev_key_release) | |
has_prev_key_release = None | |
print "on_key_press_repeat", repr(event.char) | |
else: | |
on_key_press(event) | |
frame = tkinter.Frame(tk, width=100, height=100) | |
frame.bind("<KeyRelease-a>", on_key_release_repeat) | |
frame.bind("<KeyPress-a>", on_key_press_repeat) | |
frame.bind("<KeyRelease-s>", on_key_release_repeat) | |
frame.bind("<KeyPress-s>", on_key_press_repeat) | |
frame.pack() | |
frame.focus_set() | |
tk.mainloop() |
Could you explain me how do these methods work? And why if I press the keys in quick succession, the program crashes, like a key was hold down forever?
Thank you
I don't see the advertized effect. Whenever I hold a key, I see repeated on_key_press
messages instead of just one.
this doesnt work for me on python 3...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
because i wanted t make this generic i have modified your code to create a class:
https://github.com/JamesGKent/python-tkwidgets/blob/master/Debounce.py
so any tkinter widget can be subclassed to gain this functionality, with minimal code changes, as rather than changing the bindings and creating wrapper functions, all that need be changed is the widget definition, eg
tk.Tk()
changed toDebounceTk()
whereDebounceTk
is declared as: