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 ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.