How to bind and handle events
Use bind(sequence, func)
method on your widget (like Button
or even the root app Tk
).
The parameter sequence
is one of the predefined events, a string name for keys, mouse-events, etc.
The parameter func
is a callback or handler function, given by name only (without parentheses or arguments), which must have one positional parameter for Event
.
Demo
See this minimal example:
from tkinter import *
def callback(event):
print(event)
def quit(): # did we miss something ?
print("Escape was pressed. Quitting.. Bye!")
exit()
app = Tk()
app.bind('<Return>', callback) # on keypress of Enter or Return key
app.bind('<Enter>', callback) # on mouse-pointer entering the widget - here the app's root window (not confuse with Enter key of keyboard)
app.bind('<Escape>', quit) # on keypress of Escape key
app.mainloop() # to start the main loop listening for events
Prints after following keys pressed:
- Enter key was pressed
- Escape key was pressed
<KeyPress event keysym=Return keycode=36 char='\r' x=-583 y=-309>
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
TypeError: quit() takes 0 positional arguments but 1 was given
Note:
- The Enter key was caught and bound callback/handler function (
callback
) invoked which prints the passed event
.
- The Escape key was caught and bound callback/handler function (
quit
) invoked. But since it hasn't the required parameter (like event
) the invocation failed with a TypeError
.
When adding the parameter def quit(event):
it succeeds:
<Enter event focus=True x=6 y=188>
<Enter event focus=True x=182 y=45>
<KeyPress event keysym=Return keycode=36 char='\r' x=-583 y=-309>
<Enter event state=Button1 focus=True x=123 y=68>
Escape was pressed. Quitting.. Bye!
Note:
- The
<Enter>
event is when the mouse-pointer enters the (visible) widget frame, here of the application's root window.
- The
<Escape>
event exits the application
Further reading
RealPython: Python GUI Programming With Tkinter is a rich tutorial to learn more, especially on Using .bind()
.