< BACKMake Note | BookmarkCONTINUE >
152015024128143245168232148039199167010047123209178152124239215162148036103062149000105224

Handling Tkinter Events

Usually, when you create a graphical interface for your application, you want to handle all the possible events that happen there, such as reading in each key in the keyboard (including the F1–F12 set, Ctrl, Alt, and Shift keys), tracking the actions upon the mouse button, or even controlling the window redraw events fired by the window manager. Tkinter handles that by allowing you to create bindings for every specific object. Actually, you can bind events to the widget instance itself, to the widget's Toplevel window, to the widget's class, and to your entire application (such as a global HELP functionality for the F1 function key).

After binding an event to a widget, you need to specify which function should be called at the time the event occurs. This function (or method) is called a callback. You can define callbacks for all kinds of windowing events, as you will see later. The following code demonstrates a simple callback functionality, which is associated to the command property from a specific widget.

					
from Tkinter import *
import sys
def close():
    sys.exit(0)

root = Tk()
button = Button(root)
button['text'] = "Close"
button['command'] = close
button.pack()
root.mainloop()

				

The next example binds the mouse-click event ("<Button-1>") to a specific function in our program. Note that the event description is just a simple string. The mainloop keeps checking for this event, and when it catches the event, the function (event handler) is called. Note that an object is passed to the callback function carrying some information provided by the event.

					
from Tkinter import *
def ShowPosition(event):
    Top = Toplevel(root)
    xlabel = Label(Top)
    xlabel.pack()
    xlabel.config(text = "X = " + str(event.x))
    ylabel = Label(Top)
    ylabel.pack()
    ylabel.config(text = "Y = " + str(event.y))
    Top.mainloop()

root = Tk()
frame = Frame(root, width=200, height=200)
frame.bind("<Button-1>", ShowPosition)
frame.pack()
root.mainloop()

				

The next sections provided more events that you can use in your programs.

Mouse Events

When handling mouse event, use 1 for the left button, 2 for the middle button, and 3 for the right button. The following events are based on the left button, and you need to make the necessary changes in order to adapt them for usage with the other buttons. Before starting, you should know that the current position of the mouse pointer, the position relative to the widget, is provided in the x and y options of the event object passed to the callback.

If you bind to both a single click event and to a double click event, both bindings will be called whenever one of them is activated.

<Enter>—  The mouse pointer entered the widget.

<Leave>—  The mouse pointer left the widget.

<Button-1>, <ButtonPress-1>, or <1>—  A mouse button is pressed over the widget.

<B1-Motion>—  The mouse is moved, with mouse button 1 being held down.

<ButtonRelease-1>—  Button 1 was released.

<Double-Button-1>—  Button 1 was double-clicked.

Keyboard Events

The following events are exposed by the keyboard interface:

<Key>—  The user has pressed any key. The instance object originated by the callback function carries an attribute called char that can be used to identify which key was pressed.

a—  The user typed the letter a.

b—  The user typed the letter b.

The same concept can be applied for all the other printable characters.

<Control-Up>—  The user pressed the Control key, while pressing the Up arrow. This type of structure also allows you to use the keyword suffixes Up, Down, Left, and Right, and the keyword prefixes Control, Alt, and Shift.

<Return>—  The user pressed the Enter key.

<Escape>—  The user pressed the Esc key.

The same concept can also be applied for all the other special keys found in the keyboard, including: F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Num_Lock, Scroll_Lock, Caps_Lock, Print, Insert, Delete, Pause, Prior (Page Up), Next (Page Down), BackSpace, Tab, Cancel (Break), Control_L (any Control key), Alt_L (any Alt key), Shift_L (any Shift key), End, Home, Up, Down, Left, and Right.

Event Attributes

Next, I list all the attributes that are exposed by the instance objects originated by the callback functions:

char—  Character code associated with a pressed key.

keycode—  Key code associated with a pressed key.

keysym—  Key symbol associated with a pressed key.

height, width—  New size, in pixels, of a widget.

num—  This attribute contains the mouse's button number associated with an event.

widget—  Widget instance of the widget that has generated the event.

x, y—  Current position, in pixels, of the mouse.

x_root, y_root—  These attributes identify the current position of the mouse, in pixels, relative to the upper left corner of the screen.

type—  Shows the event type.

Event Callbacks

The following methods are used to handle event callbacks by binding a Python function or method to an action that can be applied to a widget. You will also find some callback methods that handle alarm callbacks as well.

after(milliseconds [, callback [, arguments]])—  Registers an alarm callback that accepts optional arguments. This callback is called after the given number of milliseconds. The returned value of this method is an identifier that can be used along with the after_cancel method in order to cancel the callback. If you call the after method using just the first argument, the application will block the event loop and wait for the given number of milliseconds.

after_cancel(identifier)—  Cancels the alarm callback that possesses the given identifier.

after_idle(callback, arguments)—  Registers a callback that is called whenever the system is idle, without anything going on in the mainloop.

bindtags()—  Returns the binding search order used by the widget. The returned value is in a tuple format, and it lists the namespaces used to search for the bindings. You can modify this order by calling this method with the altered order as an argument.

bind(event, callback)—  Defines the function or method (callback) that must be associated to the given event. Use the form bind(event, callback, "+") to handle multiple callbacks within the same binding.

bind_all(event, callback)—  Defines the function or method (callback) that must be associated to the given event at the application level. Use the form bind_all(event, callback, "+") to handle multiple callbacks within the same binding. As an example, this can be used to set global accelerator/shortcut keys.

bind_class(widgetclass, event, callback)—  Defines the function or method (callback) that must be associated to the given event at the given widget class. Use the form bind_class(widgetclass, event, callback, "+") to handle multiple callbacks within the same binding.

<Configure>—  Indicates that the widget was resized or moved to a new location. The instance object originated by the callback function carries two attributes that can be used to identify the new size of the widget: height and width. Note that the name comes from the fact that the configure event is emitted in X11 when a window is mapped or resized.

unbind(event)—  Removes the bindings for the given event.

unbind_all(event)—  Removes the bindings for the given event at the application level.

unbind_class(class, event)—  Removes the bindings for the given event at the given widget class.

Protocols

The mechanism called protocol handler is responsible for the communication between the window manager and your application. Handling these protocols, you can intercept the messages provided by the system, and define exactly what you want to happen.

Usually, the protocols WM_DELETE_WINDOW, WM_TAKE_FOCUS, and WM_SAVE_YOURSELF are the ones mostly used. For details about the other supported protocols, see the Inter-Client Communication Conventions Manual (ICCCM) at

http://tronche.com/gui/x/icccm/

Although this convention was established for the X systems, the Tk library handles it on all platforms. These protocols are X specific. If you are running an X server on Windows or MacOS and have Tk compiled for X, it will do the same as on UNIX. That's because Tk ports map these calls to the equivalent actions on the other systems.

The necessary syntax to bind a handler to a protocol is

						
widget.protocol(protocol, function_handler)

					

Note that the widget must be a Toplevel widget. The following example demonstrates the use of the WM_DELETE_WINDOW protocol. The window manager generates this protocol when the user tries to close a window. Here, we are intercepting this protocol.

						
from Tkinter import *
import tkMessageBox
def protocolhandler():
    if tkMessageBox.askokcancel("Exit", "Wanna leave?"):
        if tkMessageBox.askokcancel("Exit", "Are you sure?"):
            if tkMessageBox.askokcancel("Exit", "Really?"):
                root.destroy()

root = Tk()
root.protocol("WM_DELETE_WINDOW", protocolhandler)
root.mainloop()

					

Just to let you know, the WM_SAVE_YOURSELF protocol is called by X window managers when the application should save a snapshot of its working set, and the WM_TAKE_FOCUS protocol is called by X window managers when the application gets the focus.


Last updated on 1/30/2002
Python Developer's Handbook, © 2002 Sams Publishing

< BACKMake Note | BookmarkCONTINUE >

Index terms contained in this section

<
      B1-Motion event
      Button-1 event
      ButtonRelease-1 event
      Configure method
      Control-Up event
      Double-Button-1 event
      Enter event
      Key event
      Leave event
      Return event
(<
     Σ
            Button-1Σ) event
a event
after(milliseconds [, callback [, arguments]]) method
after_cancel(identifier) method
after_idle(callback, arguments) method
attributes
      char
      events
      height
      keysym
      num
      widget
      x
      x_root
b event
bind(event, callback) method
bind_all(event, callback) method
bind_class(widgetclass, event, callback) method
binding
     events
            widgets 2nd 3rd 4th 5th 6th
      handlers, protocols
bindtags() method
callback function
callbacks
     events
            methods 2nd
char attribute
command property
events
     <
            B1-Motion
            Button-1
            ButtonRelease-1
            Control-Up
            Double-Button-1
            Enter
            Key
            Leave
            Return
     (<
            ΣButton-1Σ)
      a
      b
     binding
            widgets 2nd 3rd 4th 5th
     handling
            Tkinter module 2nd 3rd 4th 5th
functions
      callback
graphical user interfaces (GUIs)
     Tkinter
            handling events 2nd 3rd 4th 5th
handlers
      binding, protocols
handling
     events
            Tkinter module 2nd 3rd 4th 5th
height attribute
ICCCM (Inter-Client Communication Conventions Manual)
Inter-Client Communication Conventions Manual (ICCCM)
interfaces
     graphical user (GUI)
            Tkinter 2nd 3rd 4th 5th
keyboard events
      handling
keysym attribute
methods
     <
            Configure
      after(milliseconds [, callback [, arguments]])
      after_cancel(identifier)
      after_idle(callback, arguments)
      bind(event, callback)
      bind_all(event, callback)
      bind_class(widgetclass, event, callback)
      bindtags()
      event callbacks 2nd
      unbind(event)
      unbind_all(event)
      unbind_class(class, event)
modules
     Tkinter
            handling events 2nd 3rd 4th 5th
mouse events
      handling
num attribute
properties
      command
protocols
     handling
            Tkinter
      WM_SAVE_YOURSELF
      WM_TAKE_FOCUS
Tkinter module
      handling events 2nd 3rd 4th 5th
unbind(event) method
unbind_all(event) method
unbind_class(class, event) method
widget attribute
widgets
      binding events 2nd 3rd 4th 5th 6th
WM_SAVE_YOURSELF protocol
WM_TAKE_FOCUS protocol
x attribute
x_root attribute

© 2002, O'Reilly & Associates, Inc.