Tkinter Event Binding

Summary: in this tutorial, you’ll learn about the Tkinter event binding mechanism.

Introduction to the Tkinter event binding

Assigning a function to an event of a widget is called event binding. When the event occurs, the assigned function is invoked automatically.

In the previous tutorial, you learned how to bind a function to an event of a widget via the command option. However, not all Tkinter widgets support the command option.

Therefore, Tkinter provides you with an alternative way for event binding via the bind() method.

The following shows the general syntax of the bind() method:

widget.bind(event, handler, add=None)

When an event occurs in the widget, Tkinter will invoke the handler automatically with the event detail.

If you want to register an additional handler, you can pass the '+' to the add argument. It means that you can have multiple event handlers that respond to the same event.

Tkinter event binding examples

The following program illustrates how to bind the return_pressed function to the Return key pressed event of the 'Save' button:

import tkinter as tk from tkinter import ttk def return_pressed(event): print('Return key pressed.') root = tk.Tk() btn = ttk.Button(root, text='Save') btn.bind('<Return>', return_pressed) btn.focus() btn.pack(expand=True) root.mainloop()
Code language: Python (python)

In this example, the following statement calls the bind() method on the button widget to bind the Return key pressed event:

btn.bind('<Return>', return_pressed)
Code language: HTML, XML (xml)

The following example illustrates how to use the bind() method to register multiple handlers for the same event:

import tkinter as tk from tkinter import ttk def return_pressed(event): print('Return key pressed.') def log(event): print(event) root = tk.Tk() btn = ttk.Button(root, text='Save') btn.bind('<Return>', return_pressed) btn.bind('<Return>', log, add='+') btn.focus() btn.pack(expand=True) root.mainloop()
Code language: Python (python)

When you move the focus to the button and press the Return key, Tkinter automatically invokes the return_pressed and log functions.

The following binds the log() function to the Return key pressed event of the 'Save' button:

btn.bind('<Return>', log, add='+')
Code language: Python (python)

In this statement, the third argument add='+' registered additional handler, which is the log() function.

If you don’t specify the add='+' argument, the bind() method will replace the existing handler (return_pressed) by the new one (log).

Event patterns

Tkinter uses event patterns to map event names with handlers. For example, the <Return> denotes the Return key pressed.

The following shows the general syntax of an event pattern:

<modifier-type-detail>
Code language: HTML, XML (xml)

In this syntax, an event is surrounded by angle brackets (<>). Inside the angle brackets, there are zero or more modifiers, an event type, and detailed information of the event.

For example, the <KeyPress-A> denotes a keyboard press of the key A . and <Alt-Control-KeyPress-KP_Delete> represents a keypress of Alt + Ctrl + Delete.

The following section shows the most commonly used event modifiers, event types, and event details.

1) Event modifiers

The following table lists the most commonly used event modifiers:

Event ModifierMeaning
AltThe Alt key is held
ControlThe Ctrl key is held
ShiftThe Shift key is held
AnyThis modifier makes an event type general. For example, the event pattern <Any-KeyPress> applies to the keypress of any key.

Event types

The following table shows the most commonly used event types:

TypeNameDescription
36ActivateThe state option of a widget changes from inactive to active.
4ButtonOne mouse button is pressed
5ButtonReleaseOne mouse button is released
22ConfigureThe size of the widget is changed
37DeactivateThe state option of a widget change from active to inactive.
17DestroyA widget is being destroyed.
7EnterThe mouse pointer is moved into a visible part of a widget.
12ExposeSome part of the widget or application is visible after having been covered up by another window.
9FocusInThe input focus was moved into a widget.
10FocusOutThe input focus was moved out of a widget.
2KeyPressA key is pressed.
3KeyReleaseA key is released
8LeaveThe mouse pointer is moved out of a widget.
19MapA widget is being placed on a container e.g., calling the pack() or grid() method.
6MotionThe mouse pointer is moved entirely within a widget.
38MouseWheelThe user moved the mouse wheel up or down.
18UnmapA widget is being unmapped and is no longer visible, for example when calling the grid_remove() method on the widget.
15VisibilityAt least some part of the application window becomes visible on the screen.

Event Detail

The following table shows several ways to name keys:

.keysym.keycode.keysym_numKey
Alt_L6465513The left-hand alt key
Alt_R11365514The right-hand alt key
BackSpace2265288backspace
Cancel11065387break
Caps_Lock6665549CapsLock
Control_L3765507The left-hand control key
Control_R10965508The right-hand control key
Delete10765535Delete
Down10465364
End10365367end
Escape965307esc
Execute11165378SysReq
F16765470Function key F1
F26865471Function key F2
Fi66+i65469+iFunction key Fi
F129665481Function key F12
Home9765360home
Insert10665379insert
Left10065361
Linefeed54106Linefeed (control-J)
KP_090654380 on the keypad
KP_187654361 on the keypad
KP_288654332 on the keypad
KP_389654353 on the keypad
KP_483654304 on the keypad
KP_584654375 on the keypad
KP_685654326 on the keypad
KP_779654297 on the keypad
KP_880654318 on the keypad
KP_981654349 on the keypad
KP_Add8665451+ on the keypad
KP_Begin8465437The center key (same key as 5) on the keypad
KP_Decimal9165439Decimal (.) on the keypad
KP_Delete9165439delete on the keypad
KP_Divide11265455/ on the keypad
KP_Down8865433↓ on the keypad
KP_End8765436end on the keypad
KP_Enter10865421enter on the keypad
KP_Home7965429home on the keypad
KP_Insert9065438insert on the keypad
KP_Left8365430← on the keypad
KP_Multiply6365450× on the keypad
KP_Next8965435PageDown on the keypad
KP_Prior8165434PageUp on the keypad
KP_Right8565432→ on the keypad
KP_Subtract8265453- on the keypad
KP_Up8065431↑ on the keypad
Next10565366PageDown
Num_Lock7765407NumLock
Pause11065299pause
Print11165377PrintScrn
Prior9965365PageUp
Return3665293Enter key
Right10265363
Scroll_Lock7865300ScrollLock
Shift_L5065505The left-hand shift key
Shift_R6265506The right-hand shift key
Tab2365289The tab key

Binding events to root window

So far, you have learned how to bind an event to a particular widget. Tkinter also allows you to bind an event to the top-level window.

In this case, the syntax for the bind() is the same except that you can call it on the root window like this:

root.bind('<Return>', handler)
Code language: HTML, XML (xml)

The levels of binding

In the previous example, you have learned how to bind an event to a particular instance of a widget. This is called an instance-level binding.

Tkinter also allows you to bind an event to all the instances of a widget. For example, you can bind the event to all the textboxes in a program:

root.bind_class('Entry', '<Control-V>', paste)
Code language: JavaScript (javascript)

By the way, you use the Entry widget to create a textbox in Tkinter.

This is called class-level binding because you bind the event to a class instead of an instance.

Unbinding events

Sometimes, you may want to undo the effect of an earlier binding. To do it, you can use the unbind() method:

widget.unbind(event)
Code language: CSS (css)

The following example unbinds the event from the btn button:

btn.unbind('<Return>')
Code language: HTML, XML (xml)

Summary

  • Use the bind() method to bind an event to a widget.
  • Tkinter supports both instance-level and class-level bindings.
Did you find this tutorial helpful ?