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!

3
  • depends on the os ... but I believe you can use kbhit Commented Jan 20, 2015 at 21:57
  • I'm running Linux, just fyi Commented Jan 20, 2015 at 22:02
  • in that case I would look at this thread stackoverflow.com/questions/292095/… Commented Jan 20, 2015 at 22:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

How is this solution?
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?
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].
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.