How to Handle Keyboard Events with tkinter in Python

In this example, we will create a window with a text field to show the results corresponding to different keyboard events.

2. Keyboard Events

Tkinter can handle all keyboard events, including special keys such as Ctrl, Alt, F1, Home.

The following are keyboard events:

  • “Key”: This event occurs when the ASCII code is 48~90, which is the number key, the letter key, and the symbols (+) and (~).
  • “Control-Up”: This event occurs when the Ctrl+Up key is pressed. For the same reason, you can use a similar name in Alt, Shift plus Up, Down, Left, and Right.
  • For other buttons, use their button name. Includes: “Return”, “Escape”, “F1”, “F2”, “F3”, “F4”, “F5”, “F6”, “F7”, “F8”, “F9”, “F10”, “F11”, “F12”, “Num_Lock”, “Scroll_Lock”, “Caps_Lock”, “Print”, “Insert”, “Delete”, “Pause”, “Prior”(Page Up), “Next”(Page Down ), “BackSpace”, “Tab”, “Cancel”(Break), “Control_L” (any Ctrl key), “Alt_L” (any Alt key), “Shift_L” (any Shift key), “End”, “Home”, “Up”, “Down”, “Left”, “Right”.

In this example, we will create a window and create a text label inside the window. All keyboard events are processed in the main window, and the symbol and ASCII code of the keyboard is shown in the text tag when the button is pressed.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

from tkinter import *

# process press keyboard event
def handleKeyEvent(event):
    label1["text"] = "You press the " + event.keysym + " buttonn"    
    label1["text"] += "keycode = " + str(event.keycode)

# create the main window
win = Tk()
frame = Frame(win, relief=RAISED, borderwidth=2, width=300, height=200)

# link keyboard event to main window
eventType = ["Key", "Control-Up", "Return", "Escape", "F1", "F2", "F3", "F4", "F5", 
  "F6", "F7", "F8", "F9", "F10", "F11", "F12", "Num_Lock", "Scroll_Lock", 
  "Caps_Lock", "Print", "Insert", "Delete", "Pause", "Prior", "Next", "BackSpace", 
  "Tab", "Cancel", "Control_L", "Alt_L", "Shift_L", "End", "Home", "Up", "Down", 
  "Left", "Right"]       

for type in eventType:
    win.bind("<" + type + ">", handleKeyEvent)

label1 = Label(frame, text="No keyboard pressed now", foreground="#000fff", background="#fff000"), y=18)

# set location

# event loop

When no button is pressed:

When pressing button “S”:

Notify of
Inline Feedbacks
View all comments