Tkinter Keypress Event (Python)

vegaseat 1 Tallied Votes 15K Views Share

If you press any key on your keyboard, this small Tkinter GUI program will tell you which key and what type of key has been pressed. Great for applications where a simple key stroke is required.

# bind and show a key press event with Tkinter
# tested with Python24      vegaseat     20nov2006

from Tkinter import *

root = Tk()
prompt = '      Press any key      '
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()

def key(event):
    if event.char == event.keysym:
        msg = 'Normal Key %r' % event.char
    elif len(event.char) == 1:
        msg = 'Punctuation Key %r (%r)' % (event.keysym, event.char)
    else:
        msg = 'Special Key %r' % event.keysym
    label1.config(text=msg)

root.bind_all('<Key>', key)

root.mainloop()

Dani AI

Generated

A couple of practical tips can make Tkinter key handling more robust and portable:

  • Prefer event.keysym for the key identity and event.char for the printable character. event.char is empty for non-printable keys (e.g., arrows, function keys), while event.keysym yields names like Return, Escape, Left, F5, etc. Avoid event.keycode for logic because it varies by platform and keyboard layout. See the official Tk bind and keysym docs for the canonical names and modifiers (tcl.tk bind man page, tcl.tk keysyms).

  • If you need modifiers (Ctrl, Shift, Alt), combine event.keysym with event.state bitmasks rather than guessing from event.char. The bind manual lists the masks and how to specify modifiers in event sequences (e.g., Control-Return).

  • Ensure the correct widget has focus or your handler will not fire. Set focus explicitly when your UI launches or when a typing exercise starts (e.g., give focus to a Canvas or an Entry). You can bind at different scopes: widget-level .bind, toplevel, or application-wide with .bind_all. To suppress default behavior (like inserting into an Entry), return "break" from the handler. Details are in Python’s tkinter docs under Events and Bindings (docs.python.org tkinter).

  • Key repeat generates multiple KeyPress events. If you only want the first press, track pressed keys and clear on KeyRelease. For international input and dead keys, prefer reacting to text changes in widgets rather than raw KeyPress. For timed drills, combine key events with after() timers or time.perf_counter() to measure intervals.

Webtest 0 Newbie Poster

Thank you very much. This is a GREAT example code snippet and exactly what I need to get started on a 'Typing Exercise' program. I can't wait to try it out (but it's 2 AM!).

Blessings in abundance, & all the best!
Art in Carlisle, PA USA

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.