Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 40 ยท Events and Bindings

Tkinter bind() and Event Handling

Handle events in Tkinter with bind: event patterns, the event object, bind_all and bind_class, bindtags order, returning break, virtual events and event_generate.

The command option covers the common case of "something was clicked". Everything else (a key pressed, the mouse entering a widget, a drag, a resize, focus changes) is handled with bindings. A binding connects an event pattern to a function: when a matching event reaches a widget, Tk calls the function with an event object that describes what happened.

The basics of bind

Python
import tkinter as tk

def on_click(event):
    print(f"clicked at ({event.x}, {event.y}) on {event.widget}")

root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=200, bg="white")
canvas.pack()
canvas.bind("<Button-1>", on_click)       # <Button-1> = left mouse button press
root.mainloop()

widget.bind(pattern, function) registers the handler. The handler receives one argument, the event. (A command= function receives none; this is the main difference between the two.) A handler can be a regular function, a method (self.on_click) or a lambda: lambda event: print(event.keysym). bind returns an id that you can pass to unbind:

Python
binding_id = canvas.bind("<Button-1>", on_click)
canvas.unbind("<Button-1>", binding_id)
canvas.bind("<Button-1>", on_other, add="+")   # add a handler without replacing the old one

Without add="+", a second bind for the same pattern replaces the first. That is a classic source of "my handler stopped working".

Event patterns

A pattern is written in angle brackets: <modifier-modifier-type-detail>.

Part Examples
Type Button (or ButtonPress), ButtonRelease, Motion, Enter, Leave, KeyPress (or Key), KeyRelease, FocusIn, FocusOut, Configure, MouseWheel, Destroy
Detail A mouse button number (1, 2, 3) or a key name (a, Return, space, F5)
Modifier Control, Shift, Alt, Double, Triple, Button1 (held during motion)

Examples: <Button-1>, <B1-Motion> (drag with left button), <Double-Button-1>, <Control-s>, <Shift-Tab>, <KeyPress-a>, <Return>, <Enter>, <Leave>, <FocusOut>, <Configure>. Shortcuts exist: <Key-a> is <a> and a plain letter without brackets ("a") is a keypress of that letter. Keyboard and mouse details are in Keyboard and Mouse Events.

The event object

The event argument carries the details:

Attribute Meaning
widget The widget that received the event
x, y Pointer position relative to that widget
x_root, y_root Pointer position on the screen
char, keysym, keycode Character typed, symbolic key name ("Return", "a", "Escape"), hardware code
num Mouse button number
delta Mouse wheel direction and amount
width, height New size in <Configure> events
state Modifier bit mask
type Event type

Which handler wins? Specificity

Several patterns can match one event. Tk picks the most specific pattern of those bound to the same widget. A binding for <Control-Button-1> beats <Button-1>, and <Double-Button-1> beats <Button-1> when a double-click occurs. The stand-in below implements pattern parsing and picks the winner by counting modifiers, which explains why adding a modifier makes a handler take over.

Python Stand-in: pattern parsing and specificity

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.

The model skips many real details, but the ranking idea is the same: more modifiers and a specific detail mean a more specific pattern, and the most specific one runs.

bind, bind_all and bind_class

Call Scope
widget.bind(...) This one widget
toplevel.bind(...) The toplevel and every widget inside it (see bindtags)
widget.bind_all(...) Every widget in the application, any window
widget.bind_class("Entry", ...) Every widget of a class, for example all Entry widgets

bind_all is the right place for app-wide shortcuts, such as bind_all("<Control-q>", quit) or <F1> for help. bind_class changes the behaviour of all widgets of a type: root.bind_class("Entry", "<Control-a>", select_all) fixes Ctrl+A in every entry at once.

Bindtags: the order of handlers

When an event hits a widget, Tk runs bindings from a list of binding tags, in order. For a typical widget the list is:

  1. The widget itself.
  2. Its widget class ("Entry", "Button", ... where the built-in behaviour lives).
  3. The toplevel window that contains it.
  4. "all" (the bind_all bindings).

You can see it with widget.bindtags(). This ordering explains two common problems.

Your handler runs before the default one. Binding <KeyPress> on an Entry runs before the class binding that inserts the character. In your handler, entry.get() does not yet contain the key. If you want the text after the key press, bind <KeyRelease> instead or use a StringVar trace.

Stopping the default behaviour. If your widget-level handler returns the string "break", Tk skips all remaining tags, including the class binding that would have done the default action:

Python
def block_spaces(event):
    return "break"                 # swallow the key: no space is inserted

entry.bind("<space>", block_spaces)

Without "break" the space is typed. You can model the effect:

Python Stand-in: bindtags and 'break'

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.

Virtual events

A virtual event has a name in double angle brackets, such as <<Copy>>, <<ListboxSelect>> or <<ComboboxSelected>>. Tk generates them for high-level actions, and they are portable (<<Copy>> means Ctrl+C on Windows and Cmd+C on macOS). You can define your own and trigger them from code:

Python
root.event_add("<<Save>>", "<Control-s>", "<Command-s>")       # two key combos, one event
root.bind("<<Save>>", lambda e: save_document())

def on_data_loaded():
    table.event_generate("<<DataLoaded>>")                     # notify listeners

table.bind("<<DataLoaded>>", refresh_summary)

Virtual events are the clean way for components to talk without knowing each other: the sender generates <<Something>>, anyone interested binds it. event_generate can also simulate input (entry.event_generate("<Key-a>"), canvas.event_generate("<Button-1>", x=10, y=10)), useful for tests.

Common mistakes

  • Forgetting that handlers take event. bind("<Return>", save) fails with a TypeError if save() takes no argument. Use lambda event: save() or define def save(event=None).
  • Binding a slow handler to <Motion>. It runs for every mouse movement; keep it fast.
  • Replacing instead of adding. Use add="+".
  • Reading widget text in <KeyPress>. It is the text before the key.
  • Binding <Configure> on the toplevel and being flooded by child events: check event.widget.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you bind() the same pattern twice on one widget without add='+'?

    Each bind replaces the previous binding for that pattern unless add='+' is given.
  2. 2. Why does entry.get() inside a <KeyPress> handler not include the new character?

    Bindtags order is widget, class, toplevel, all. Use <KeyRelease> or a StringVar trace to see the updated text.
  3. 3. What does returning 'break' from a handler do?

    'break' skips later tags such as the class binding, so the default action does not happen.
  4. 4. Which call defines a shortcut for the whole application?

    bind_all applies to every widget in the application, which suits global shortcuts.

Summary

  • widget.bind("<pattern>", handler) runs handler(event); add add="+" to keep existing bindings.
  • Patterns combine modifiers, an event type and a detail (<Control-Button-1>, <KeyPress-a>); the most specific match wins.
  • The event object gives position, widget, key and size details.
  • bind_all and bind_class widen the scope; bindtags run widget, class, toplevel, then all, and "break" stops the chain.
  • Virtual events (<<Name>>, event_add, event_generate) let components communicate cleanly.

Next: Keyboard and Mouse Events