2

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!

Vasu
  • 1,090
  • 3
  • 18
  • 35

1 Answers1

3

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.

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • How is this solution? – Malik Brahimi Jan 20 '15 at 22:18
  • I haven't tested this yet, but the behavior that I've noticed is that the events keep firing - that is, both the keyup and keydown events fire repeatedly (keyup, keydown, keyup, keydown, etc...) while the key is being held down. If I'm not mistaken, storing the states won't help alleviate this issue? – Vasu Jan 21 '15 at 03:54
  • Tested, and the same behavior seems to be happening - that is, with a single key depressed, the `keys` variable is cycling between one entry and 0 entries, i.e. `[]` and `[112]`. – Vasu Jan 21 '15 at 07:23
  • I gave you a push in the right direction. Now you need to create a second list for the previous state that you can compare to the current state. This will allow you to determine a single key press. – Malik Brahimi Jan 23 '15 at 00:35