ZetCode

Tk events and bindings

last modified November 24, 2026 Tcl 8.6

A Tk program does not run from top to bottom. It creates widgets, registers callbacks, and then waits in mainloop. Everything that happens afterwards, a click, a key press, a window manager message, arrives as an event, and Tk dispatches it to the widgets that asked for it. bind is the command that says which script runs for which event.

This article covers event patterns, the substitutions that carry event details into a script, the tag order that decides which bindings fire, virtual events, and the window manager protocol. It ends with a keyboard-driven widget and with event generate, the command that lets a test drive a GUI without a person at the keyboard. The after command, used here to close windows, is covered in its own article.

bind and event patterns

bind takes a widget, an event pattern and a script. The pattern is written in angle brackets: <Button-1> is a press of the first mouse button, <KeyPress> any key, and <Control-Key-s> the letter s with Control held. A pattern can also contain a detail such as <Double-Button-1> or a modifier. Calling bind again with the same pattern replaces the script, and calling it without a script returns the current one.

bind_intro.tcl
package require Tk

wm geometry . 320x140
label .msg -text "click me" -font {Helvetica 14}
pack .msg -padx 20 -pady 30

bind .msg <Button-1> {puts "clicked at %x,%y"}
puts "binding: [bind .msg <Button-1>]"

update
event generate .msg <Button-1> -x 10 -y 12
after 300 {destroy .}

The script registers a click handler on a label and then generates the click itself. update is needed before the generated event: a window that has not been mapped yet does not receive pointer events, and update gives Tk the chance to map it. Inside the handler, %x and %y are replaced with the pointer coordinates before the script runs.

$ wish bind_intro.tcl
binding: puts "clicked at %x,%y"
clicked at 10,12

Mouse and keyboard events

Pointer motion is reported by <Motion>, entering a widget by <Enter> and leaving it by <Leave>. Keys arrive as <KeyPress> with the key in the detail, and named keys have their own patterns such as <Return>, <Up> or <Escape>. A widget receives key events only when it has the keyboard focus.

mouse_key.tcl
package require Tk

frame .f -width 220 -height 120 -background white
pack .f -padx 10 -pady 10

bind .f <Enter> {puts "pointer entered"}
bind .f <Leave> {puts "pointer left"}
bind .f <Motion> {puts "motion at %x,%y"}
bind .f <KeyPress> {puts "key %A (keysym %K)"}
bind .f <Return> {puts "return pressed"}

focus -force .f
update
event generate .f <Enter>
event generate .f <Motion> -x 40 -y 20
event generate .f <KeyPress-a>
event generate .f <Return>
event generate .f <Leave>
after 300 {destroy .}

The frame has five bindings and each one prints a line. The script calls focus -force .f before generating the keys, because there is no window manager in a headless test to give the window focus; in a normal session the user clicks the window and the window manager assigns focus. The %A substitution holds the character and %K the keysym, which is why a appears twice in the key line.

$ wish mouse_key.tcl
pointer entered
motion at 40,20
key a (keysym a)
return pressed
pointer left

% substitutions

A binding script can contain substitutions, written with a percent sign, that Tk replaces with details of the event. %W is the widget that received the event, %x and %y are coordinates inside it, %b is the button number, %A is the character, %K the keysym, and %s the state of the modifier keys. The full list is in the bind manual page.

Substitutions belong in a script that is evaluated for every event. When the handler is a procedure, build the command with list: the substitutions then become ordinary arguments, so values with spaces stay one argument and no quoting problem arises.

substitutions.tcl
package require Tk

proc report {window x y button} {
    puts "window=$window x=$x y=$y button=$button"
}

label .box -text "target" -font {Helvetica 14} -width 12
pack .box -padx 20 -pady 20
bind .box <Button-1> [list report %W %x %y %b]

update
event generate .box <Button-1> -x 5 -y 7
after 300 {destroy .}

bind .box <Button-1> [list report %W %x %y %b] creates the command report %W %x %y %b once. At click time Tk substitutes the four values and calls report with four arguments, which the procedure names window, x, y and button. Braces would work as well for a one-line script; building the command with list keeps the argument boundaries explicit and is the usual style when the handler is a procedure.

$ wish substitutions.tcl
window=.box x=5 y=7 button=1

bindtags

Every widget carries a list of binding tags. Tk walks that list for each event and runs the first matching binding of each tag. The default list is the widget path, the widget class, the toplevel window and all, so a binding on the class applies to every widget of that class and a binding on all applies to the whole application.

tag_order.tcl
package require Tk

entry .text
pack .text -padx 10 -pady 10
focus -force .text

puts "tags: [bindtags .text]"

bind Logger <KeyPress> {puts "Logger tag saw %A"}
bindtags .text [linsert [bindtags .text] 1 Logger]
puts "new tags: [bindtags .text]"

update
event generate .text <KeyPress-q>
puts "content: [.text get]"
after 300 {destroy .}

bindtags .text shows the four default tags. The script inserts a custom tag Logger at position 1, after the widget itself and before the class. The generated q is seen by the Logger binding first and then by the Entry class binding, which inserts the character; the final content confirms that both ran. A binding that ends with break would stop the walk at that tag.

$ wish tag_order.tcl
tags: .text Entry . all
new tags: .text Logger Entry . all
Logger tag saw q
content: q

Virtual events

A virtual event has a name in double angle brackets, such as <<Paste>> or <<ClearAll>>, and is not tied to one physical key. event add attaches one or more patterns to the name, event info lists them, and bind works with the name like with any other pattern. Virtual events let an application describe what happened instead of which key was pressed.

virtual.tcl
package require Tk

event add <<ClearAll>> <Control-Key-x> <Control-Key-X>
puts "patterns: [event info <<ClearAll>>]"

label .status -text "two lines of notes" -width 24 -anchor w
pack .status -padx 10 -pady 10
bind .status <<ClearAll>> {
    .status configure -text "cleared"
    puts "clear requested"
}

update
event generate .status <<ClearAll>>
puts "label now: [.status cget -text]"
after 300 {destroy .}

The name <<ClearAll>> is bound to Control-x and to Control-Shift-x, because Tk treats x and X as different keysyms. The binding changes the label text, and the script then reads the text back to prove that the handler ran. A larger program can generate the same virtual event from a menu entry, a toolbar button and a key binding, and keep a single handler for all three.

$ wish virtual.tcl
patterns: <Control-Key-x> <Control-Key-X>
clear requested
label now: cleared

wm protocol WM_DELETE_WINDOW

The close button of a window is not a widget in the Tk application. The window manager sends the WM_DELETE_WINDOW message to the toplevel, and Tk runs the handler registered with wm protocol. Without a handler Tk destroys the window; with one, the program can save data, ask for confirmation, or ignore the request.

protocol.tcl
package require Tk

proc close_window {} {
    puts "saving settings"
    destroy .
}

wm protocol . WM_DELETE_WINDOW close_window
puts "handler: [wm protocol . WM_DELETE_WINDOW]"

after 300 close_window

The handler is a procedure that prints a message and destroys the main window, which ends the application. wm protocol . WM_DELETE_WINDOW without a script returns the registered command, which the script prints for confirmation. In the test the handler is called by a timer instead of by a window manager, so the example finishes on its own; in a real session the same procedure runs when the user clicks the close button.

$ wish protocol.tcl
handler: close_window
saving settings

A small keyboard-driven example

The next program keeps a selection index in a global variable, shows the selected item in a label, and lets the arrow keys move the selection. It is the smallest useful example of state kept by the application and changed by events: the widget displays the state, the bindings change it, and a procedure redraws the display.

keyboard_app.tcl
package require Tk

set items {Apple Banana Cherry}
set current 0

proc refresh {} {
    .view configure -text "> [lindex $::items $::current]"
}

proc move {delta} {
    set next [expr {$::current + $delta}]
    if {$next >= 0 && $next < [llength $::items]} {
        set ::current $next
        refresh
        puts "selected: [lindex $::items $::current]"
    }
}

proc choose {} {
    puts "chosen: [lindex $::items $::current]"
}

label .view -text "" -font {Helvetica 16} -width 20 -anchor w
pack .view -padx 20 -pady 20
focus -force .view

bind .view <Up> {move -1}
bind .view <Down> {move 1}
bind .view <Return> {choose}
refresh

update
event generate .view <Down>
event generate .view <Down>
event generate .view <Return>
after 300 {destroy .}

move checks the new index against the list bounds before storing it, so holding Down at the last item does nothing. refresh reads the global list and index and writes the label text; calling it once before the event loop starts gives the window its initial content. The test generates Down twice and Return once, and the output shows the selection moving and the final choice.

$ wish keyboard_app.tcl
selected: Banana
selected: Cherry
chosen: Cherry

event generate for testing

event generate sends a synthetic event to a widget. GUI tests use it to press buttons, type text and move the pointer without a display or a person. The widget must be mapped, which update takes care of, and a button also expects the pointer to be over it, so the test generates <Enter> before the press and release.

generate_test.tcl
package require Tk

set clicks 0
button .b -text "Count" -command {
    incr ::clicks
    puts "command ran, clicks = $::clicks"
}
pack .b -padx 20 -pady 20

update
event generate .b <Enter>
event generate .b <ButtonPress-1> -x 10 -y 10
event generate .b <ButtonRelease-1> -x 10 -y 10
puts "after first click:  $clicks"

event generate .b <ButtonPress-1> -x 10 -y 10
event generate .b <ButtonRelease-1> -x 10 -y 10
puts "after second click: $clicks"
after 300 {destroy .}

Each pair of press and release events runs the button command once, and the counter proves it. The <Enter> event matters: Tk remembers which widget the pointer is in, and the class binding invokes the command only when that widget is the button. Tests that skip the <Enter> see a press that changes the relief and a release that does nothing, which is a common source of confusion.

$ wish generate_test.tcl
command ran, clicks = 1
after first click:  1
command ran, clicks = 2
after second click: 2

Source

The Tk 8.6 manual documents bind, bindtags, event and wm, which are the commands behind this article. The Tcl manual covers the event loop that delivers the events.

This article explained how Tk turns user actions into events, how bind connects patterns to scripts, how substitutions pass event details, how bindtags order the handlers, and how virtual events and the window manager protocol fit in. Continue with Tcl after to schedule work inside the same event loop, or with vwait to see how a script waits for an event.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.