Skip to content

Instantly share code, notes, and snippets.

@vtsatskin
Created October 13, 2015 17:32
Show Gist options
  • Save vtsatskin/8e3c0c636339b2228138 to your computer and use it in GitHub Desktop.
Save vtsatskin/8e3c0c636339b2228138 to your computer and use it in GitHub Desktop.
Listening to KeyPress and KeyRelease with Tkinter with debouncing
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()
@JamesGKent
Copy link

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 to DebounceTk() where DebounceTk is declared as:

class DebounceTk(Debounce, tk.Tk):
    pass

@Lollo-Rese
Copy link

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

@native-api
Copy link

I don't see the advertized effect. Whenever I hold a key, I see repeated on_key_press messages instead of just one.

@BenedictWilkins
Copy link

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