An event is something that happens to your application—for example, the user presses a key or clicks or drags the mouse—to which the application needs to react.
The widgets normally have a lot of built-in behaviors. For
example, a button will react to a mouse click by calling
command callback. For another example,
if you move the focus to an entry widget and press a
letter, that letter gets added to the content of the
However, the event binding capability of Tkinter allows you to add, change, or delete behaviors.
First, some definitions:
An event is some occurrence that your application needs to know about.
An event handler is a function in your application that gets called when an event occurs.
We call it binding when your application sets up an event handler that gets called when an event happens to a widget.
You can bind a handler to an event at any of three levels:
Instance binding: You can bind an event to one
specific widget. For example, you might bind the
PageUp key in a canvas widget to a
handler that makes the canvas scroll up one page. To
bind an event of a widget, call the
on that widget (see Section 26, “Universal widget methods”).
For example, suppose you have a canvas widget named
self.canv and you want to draw an
orange blob on the canvas whenever the user clicks
the mouse button 2 (the middle button). To implement
The first argument is a sequence
descriptor that tells Tkinter that
whenever the middle mouse button goes down, it is to
call the event handler named
self.__drawOrangeBlob. (See Section 54.6, “Writing your handler: The
class”, below, for an overview of
how to write handlers such as
.__drawOrangeBlob()). Note that you omit
the parentheses after the handler name, so that
Python will pass in a reference the handler instead
of trying to call it right away.
Class binding: You can bind an event to all widgets
of a class. For example, you might set up all
Button widgets to respond to middle mouse
button clicks by changing back and forth between
English and Japanese labels. To bind an event to all
widgets of a class, call the
.bind_class() method on any widget (see Section 26, “Universal widget methods”, above).
For example, suppose you have several canvases, and
you want to set up mouse button 2 to draw an orange
blob in any of them. Rather than having to call
.bind() for every one of them, you can
set them all up with one call something like this:
self.bind_class('Canvas', '<Button-2>', self.__drawOrangeBlob)
Application binding: You can set up a binding so that
a certain event calls a handler no matter what widget
has the focus or is under the mouse. For example,
you might bind the PrintScrn key to
all the widgets of an application, so that it prints
the screen no matter what widget gets that key. To
bind an event at the application level, call the
.bind_all() method on any widget (see Section 26, “Universal widget methods”).
Here's how you might bind the
PrintScrn key, whose “key