[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

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 fol-
lowing 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 7-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 for code in a script file, you really need to do steps 3 and 4 in the preceding
list to open this script’s GUI. To display a GUI’s window at all, you need to call main
loop; to display widgets within the window, they must be packed (or otherwise ar-
ranged) so that the tkinter geometry manager knows about them. In fact, if you call
either mainloop or pack without calling the other, your window won’t show up as ex-
pected: a mainloop without a pack shows an empty window, and a pack without a
mainloop in a script shows nothing since the script never enters an event wait state (try
it). The mainloop call is sometimes optional when you’re coding interactively, but you
shouldn’t rely on this in general.


Since the concepts illustrated by this simple script are at the core of most tkinter pro-
grams, let’s take a deeper look at some of them before moving on.


‡ Technically, the mainloop call returns to your script only after the tkinter event loop exits. This normally
happens when the GUI’s main window is closed, but it may also occur in response to explicit quit method
calls that terminate nested event loops but leave open the GUI at large. You’ll see why this matters in
Chapter 8.


Climbing the GUI Learning Curve | 369
Free download pdf