Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 40 ยท Events and Bindings

Tkinter Keyboard and Mouse Events

Handle keys, shortcuts, clicks, drags, double-clicks, hover and the mouse wheel in Tkinter, including keysym names, modifier state bits and cross-platform wheel handling.

The previous lesson explained how bind works. This one is about the events you will bind most often: keyboard input, mouse clicks, dragging, hovering and the mouse wheel. Each has details that differ between Windows, macOS and Linux, and a few traps that are worth knowing before they bite.

Keyboard events

Bind <KeyPress> (or <Key>) to see every key; bind a specific key with <KeyPress-a>, <Return>, <Escape> and so on. Inside the handler, three attributes tell you what was pressed:

Python
import tkinter as tk

def on_key(event):
    print(f"char={event.char!r}  keysym={event.keysym!r}  keycode={event.keycode}")

root = tk.Tk()
root.bind("<KeyPress>", on_key)
root.mainloop()
  • event.char: the character produced ("a", "A", "5", "" for keys that type nothing, such as arrows).
  • event.keysym: the symbolic name of the key, such as "a", "Return", "Escape", "Left", "F5", "space", "BackSpace", "Tab", "Shift_L". Use this to recognise special keys.
  • event.keycode: the hardware code, which differs between systems. Avoid it.

Key names are case-sensitive in patterns: <KeyPress-a> fires for a lowercase a, <KeyPress-A> for Shift plus a. Use <Control-s>, <Control-Shift-S>, <Alt-F4>; on macOS, <Command-s> replaces Ctrl for most shortcuts.

Which widget receives key events?

Keyboard events go to the widget that has focus. A Label or Canvas does not take focus by itself, so label.bind("<Key>", ...) never fires. Either bind on the window (root.bind, which hears keys from all its children, thanks to bindtags), or give the widget focus: canvas.focus_set() and/or canvas.config(takefocus=True); clicking can pass the focus with canvas.bind("<Button-1>", lambda e: canvas.focus_set()).

Shortcuts

Python
root.bind("<Control-s>", lambda e: save())
root.bind("<Control-o>", lambda e: open_file())
root.bind("<F1>", lambda e: show_help())
root.bind("<Escape>", lambda e: root.destroy())
entry.bind("<Return>", lambda e: submit())

Remember that menu accelerators shown in a menu (chapter 5) are labels only; you still bind the keys. A catch: a <Control-s> handler on the root also fires when an Entry has focus; that is usually what you want. The reverse, a letter shortcut such as <KeyPress-d> on the root, would fire while the user types a "d" in an Entry, so check event.widget or use a modifier.

Arrow-key movement

Python
SPEED = 10
def move(event):
    dx, dy = {"Left": (-SPEED, 0), "Right": (SPEED, 0), "Up": (0, -SPEED), "Down": (0, SPEED)}.get(event.keysym, (0, 0))
    canvas.move(player, dx, dy)

root.bind("<Key>", move)

For smooth games, track which keys are held by recording KeyPress and KeyRelease in a set and moving the object from an after() timer. Holding a key triggers operating-system auto-repeat, which sends repeated press and release events with delays that you cannot rely on.

Modifier state

event.state is a bit mask of modifier keys and mouse buttons. The common bits are:

Mask Meaning
0x0001 Shift
0x0002 Caps Lock
0x0004 Control
0x0008 Alt (Windows/Linux, often Num Lock on some systems)
0x0100 / 0x0200 / 0x0400 Mouse button 1 / 2 / 3 held

Platform differences exist (Alt and Command masks vary), so for production code prefer binding the modifier in the pattern (<Shift-Button-1>) instead of decoding state. For learning, decoding makes the bit mask concrete:

Python Stand-in: decode event.state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mouse buttons and clicks

Python
canvas.bind("<Button-1>", lambda e: print("left press", e.x, e.y))
canvas.bind("<ButtonRelease-1>", lambda e: print("left release"))
canvas.bind("<Button-3>", lambda e: print("right click"))       # Windows and Linux
canvas.bind("<Button-2>", lambda e: print("right click on macOS, middle elsewhere"))
canvas.bind("<Double-Button-1>", lambda e: print("double click"))
canvas.bind("<Triple-Button-1>", lambda e: print("triple click"))

Button numbers: 1 is left, 2 is middle, 3 is right on Windows and Linux. On macOS the secondary (right) button is 2, so portable code often binds both <Button-2> and <Button-3> or <Control-Button-1> too, using sys.platform to decide. The click position is event.x, event.y in the widget's coordinates and event.x_root, event.y_root on the screen.

A double-click delivers a single press first, then the double event: a widget bound to both <Button-1> and <Double-Button-1> runs both handlers on a double-click (<Double-Button-1> is the more specific one, but Tk does not suppress the plain binding on the first click). A common workaround is to delay the single-click action with after and cancel it if a double-click arrives. The model below reproduces the timing rule that decides what counts as "double":

Python Stand-in: single versus double click

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dragging

Dragging combines three events: the press (record where you started), the motion with a button held (<B1-Motion>) and the release (finish).

Python
import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=300, bg="white")
canvas.pack()
box = canvas.create_rectangle(50, 50, 120, 100, fill="#2a9d8f")

drag = {"x": 0, "y": 0}

def start(event):
    drag["x"], drag["y"] = event.x, event.y

def move(event):
    canvas.move(box, event.x - drag["x"], event.y - drag["y"])
    drag["x"], drag["y"] = event.x, event.y

canvas.tag_bind(box, "<Button-1>", start)
canvas.tag_bind(box, "<B1-Motion>", move)
root.mainloop()

The trick is to move by the difference from the last position and store the new position every time. Moving to the absolute mouse position would make the object's corner jump to the pointer. Here is the maths including a clamp that keeps the box inside its area:

Python Stand-in: drag by delta, clamped to bounds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hover: Enter and Leave

<Enter> and <Leave> fire when the pointer enters or leaves a widget. They produce hover effects and tooltips:

Python
def hover_on(event):
    event.widget.config(bg="#a8dadc")

def hover_off(event):
    event.widget.config(bg="#f1faee")

for button in buttons:
    button.bind("<Enter>", hover_on)
    button.bind("<Leave>", hover_off)

<Motion> reports every pointer movement over a widget. Keep that handler light. For tooltips, start an after(500, show) on <Enter>, cancel it on <Leave> or <Motion>, and use a borderless Toplevel (overrideredirect(True)) placed at event.x_root + 10, event.y_root + 10.

The mouse wheel

Wheel handling is the least portable part of Tkinter:

Platform Event Value
Windows <MouseWheel> event.delta in multiples of 120 (positive = up)
macOS <MouseWheel> small event.delta values (1, 2, 3...)
Linux (X11) <Button-4> (up) and <Button-5> (down) no delta

A function can normalise all three into "number of lines to scroll":

Python Stand-in: normalise wheel events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Tk, the corresponding real handler looks like this, using yview_scroll(number, "units"):

Python
import sys

def on_wheel(event):
    if sys.platform.startswith("linux"):
        step = -1 if event.num == 4 else 1
    elif sys.platform == "darwin":
        step = -event.delta
    else:
        step = -int(event.delta / 120)
    canvas.yview_scroll(step, "units")

canvas.bind("<MouseWheel>", on_wheel)         # Windows, macOS
canvas.bind("<Button-4>", on_wheel)           # Linux up
canvas.bind("<Button-5>", on_wheel)           # Linux down

For scrollable frames (Frames and LabelFrames), bind the wheel on the canvas and on the pointer-entered inner widgets, or use bind_all while the pointer is inside the region, and unbind_all on <Leave>, so the wheel does not scroll the wrong thing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which event attribute tells you that the user pressed the Escape key?

    keysym holds the symbolic key name. char is empty for non-printing keys and keycode differs between systems.
  2. 2. A Canvas has bind('<KeyPress>', handler) but the handler never runs. Why?

    Key events go to the focused widget. Non-input widgets must be given focus explicitly.
  3. 3. How should a drag handler move an object?

    Moving by deltas keeps the grab point constant; absolute moves make the object's corner jump to the pointer.
  4. 4. On Linux, how do you receive wheel scrolling?

    On X11 the wheel emulates buttons 4 (up) and 5 (down); Windows and macOS send <MouseWheel>.

Summary

  • Key events go to the focused widget; use event.keysym for special keys and bind shortcuts on root (use Command on macOS).
  • event.state is a modifier bit mask; prefer modifier patterns like <Control-Shift-S>.
  • Mouse buttons are numbered 1, 2, 3 (right-click is 2 on macOS); double-click events arrive after a single press.
  • Drag with press, <B1-Motion> and release, moving by deltas and clamping to bounds.
  • The wheel differs per platform: delta/120 on Windows, delta on macOS, Button-4/5 on Linux.

Next: Timers, Focus and Threads