Tkinter Event Binding
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 known as event binding. The assigned function is invoked automatically when the event occurs.
Unlike the command option, not all Tkinter widgets support it, so Tkinter provides an alternative way for event binding via the bind()
method.
Using the bind() Method
The general syntax of the bind()
method is:
widget.bind(event, handler, add=None)
When an event occurs in the widget, Tkinter will automatically invoke the handler with the event details. You can register additional handlers by passing '+'
to the add
argument, allowing multiple event handlers for the same event.
Tkinter Event Binding Examples
Example 1: Binding a Function to a Key Event
Here’s how to bind a function to the Return key pressed event of a 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_pressed)
btn.focus()
btn.pack(expand=True)
root.mainloop()
Code copied!
Example 2: Registering Multiple Handlers
This example shows 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_pressed)
btn.bind('', log, add='+')
btn.focus()
btn.pack(expand=True)
root.mainloop()
Code copied!
Event Patterns
Tkinter uses event patterns to map event names with handlers. For example, <Return>
denotes the Return key pressed.
The syntax for event patterns is:
<modifier-type-detail>
Modifiers can include:
Alt
: The Alt key is heldControl
: The Ctrl key is heldShift
: The Shift key is heldAny
: Applies to the keypress of any key, e.g.,<Any-KeyPress>
Binding Events to the Root Window
You can also bind an event to the top-level window:
root.bind('<Return>', handler)
Unbinding Events
If you want to undo the effect of an earlier binding, use the unbind()
method:
btn.unbind('<Return>')
Conclusion
In this tutorial, you learned about Tkinter event binding and how to use the bind()
method to create responsive applications. You also explored binding events to both individual widgets and the root window, and how to manage multiple handlers for the same event.
0 Comments