Reputation: 1110
Is it possible to cleanly detect a key being held down in (ideally native) Python (2)? I'm currently using Tkinter to handle Keyboard events, but what I'm seeing is that when I'm holding a key down, Key
, KeyPress
, and KeyRelease
events are all firing constantly, instead of the expected KeyPress
once and KeyRelease
at the end. I've thought about using the timing between events to try to differentiate between repeated firing and the actual event, but the timing seems inconsistent - thus, while doable, it seems like a pain.
Along the same lines, is there a nice way to detect multiple key presses (and all being held down?) I'd like to have just used KeyPress
and KeyRelease
to detect the start / end of keys being pressed, but that doesn't seem to be working.
Any advice is appreciated.
Thanks!
Upvotes: 2
Views: 1875
Reputation: 16711
Use a keyup and keydown handler with a global array:
keys = []
def down(event):
global keys
if not event.keycode in keys:
keys.append(event.keycode)
def up(event):
global keys
keys.remove(event.keycode)
root.bind('<KeyPress>', down)
root.bind('<KeyRelease>', up)
Now you can check for multiple entries in keys
. To remove that continuous behavior you described, you have to compare the previous state of keys
after an event happens.
Upvotes: 3