on Unix, or whatever GUI system your Python uses on your Macintosh. The portability
of tkinter actually stems from the underling Tk library it wraps.
Python’s tkinter adds a software layer on top of Tk that allows Python scripts to call
out to Tk to build and configure interfaces and routes control back to Python scripts
that handle user-generated events (e.g., mouse clicks). That is, GUI calls are internally
routed from Python script, to tkinter, to Tk; GUI events are routed from Tk, to tkinter,
and back to a Python script. In Chapter 20, we’ll know these transfers by their C inte-
gration terms, extending and embedding.
Technically, tkinter is today structured as a combination of the Python-coded
tkinter module package’s files and an extension module called _tkinter that is written
in C. _tkinter interfaces with the Tk library using extending tools and dispatches call-
backs back to Python objects using embedding tools; tkinter simply adds a class-based
interface on top of _tkinter. You should almost always import tkinter in your scripts,
though, not _tkinter; the latter is an implementation module meant for internal use
only (and was oddly named for that reason).
Programming structure
Luckily, Python programmers don’t normally need to care about all this integration
and call routing going on internally; they simply make widgets and register Python
functions to handle widget events. Because of the overall structure, though, event han-
dlers are usually known as callback handlers, because the GUI library “calls back” to
Python code when events occur.
In fact, we’ll find that Python/tkinter programs are entirely event driven: they build
displays and register handlers for events, and then do nothing but wait for events to
occur. During the wait, the Tk GUI library runs an event loop that watches for mouse
clicks, keyboard presses, and so on. All application program processing happens in the
registered callback handlers in response to events. Further, any information needed
across events must be stored in long-lived references such as global variables and class
instance attributes. The notion of a traditional linear program control flow doesn’t
really apply in the GUI domain; you need to think in terms of smaller chunks.
In Python, Tk also becomes object oriented simply because Python is object oriented:
the tkinter layer exports Tk’s API as Python classes. With tkinter, we can either use a
simple function-call approach to create widgets and interfaces, or apply object-oriented
techniques such as inheritance and composition to customize and extend the base set
of tkinter classes. Larger tkinter GUIs are generally constructed as trees of linked tkinter
widget objects and are often implemented as Python classes to provide structure and
retain state information between events. As we’ll see in this part of the book, a tkinter
GUI coded with classes almost by default becomes a reusable software component.
tkinter Overview | 367