Skip to Main Content
Programming Python, 3rd Edition
book

Programming Python, 3rd Edition

by Mark Lutz
August 2006
Intermediate to advanced content levelIntermediate to advanced
1600 pages
51h 46m
English
O'Reilly Media, Inc.
Content preview from Programming Python, 3rd Edition

Tkinter Coding Basics

The gui1 script is a trivial example, but it illustrates steps common to most Tkinter programs. This Python code does the following:

  1. Loads a widget class from the Tkinter module

  2. Makes an instance of the imported Label class

  3. Packs (arranges) the new Label in its parent widget

  4. Calls mainloop to bring up the window and start the Tkinter event loop

The mainloop method called last puts the label on the screen and enters a Tkinter wait state, which watches for user-generated GUI events. Within the mainloop function, Tkinter internally monitors things such as the keyboard and mouse to detect user-generated events. In fact, the Tkinter mainloop function is similar in spirit to the following pseudo-Python code:

def mainloop( ):
    while the main window has not been closed:
        if an event has occurred:
            run the associated event handler function

Because of this model, the mainloop call in Example 8-1 never returns to our script while the GUI is displayed on-screen.[*] When we write larger scripts, the only way we can get anything done after calling mainloop is to register callback handlers to respond to events.

This is called event-driven programming, and it is perhaps one of the most unusual aspects of GUIs. GUI programs take the form of a set of event handlers that share saved information rather than of a single main control flow. We’ll see how this looks in terms of real code in later examples.

Note that in a script, you really need steps 3 and 4 in the preceding list to open this ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python, 3rd Edition

Learning Python, 3rd Edition

Mark Lutz

Publisher Resources

ISBN: 0596009259Supplemental ContentErrata Page