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

(yzsuai) #1

Running GUI Programs


Like all Python code, the module in Example 7-1 can be started in a number of ways—
by running it as a top-level program file:


C:\...\PP4E\Gui\Intro> python gui1.py

by importing it from a Python session or another module file:


>>> import gui1

by running it as a Unix executable if we add the special #! line at the top:


% gui1.py &

and in any other way Python programs can be launched on your platform. For instance,
the script can also be run by clicking on the file’s name in a Windows file explorer, and
its code can be typed interactively at the >>> prompt.§ It can even be run from a C
program by calling the appropriate embedding API function (see Chapter 20 for details
on C integration).


In other words, there are really no special rules to follow when launching GUI Python
code. The tkinter interface (and Tk itself) is linked into the Python interpreter. When
a Python program calls GUI functions, they’re simply passed to the embedded GUI
system behind the scenes. That makes it easy to write command-line tools that pop up
windows; they are run the same way as the purely text-based scripts we studied in the
prior part of this book.


Avoiding DOS consoles on Windows


In Chapters 3 and 6 we noted that if a program’s name ends in a .pyw extension rather
than a .py extension, the Windows Python port does not pop up a DOS console box
to serve as its standard streams when the file is launched by clicking its filename icon.
Now that we’ve finally started making windows of our own, that filename trick will
start to become even more useful.


If you just want to see the windows that your script makes no matter how it is launched,
be sure to name your GUI scripts with a .pyw if they might be run on Windows. For
instance, clicking on the file in Example 7-2 in a Windows explorer creates just the
window in Figure 7-1.


Example 7-2. PP4E\Gui\Intro\gui1.pyw


...same as gui1.py...


§Tip: As suggested earlier, when typing tkinter GUI code interactively, you may or may not need to call
mainloop to display widgets. This is required in the current IDLE interface, but not from a simple interactive
session running in a system console window. In either case, control will return to the interactive prompt
when you kill the window you created. Note that if you create an explicit main-window widget by calling
Tk() and attach widgets to it (described later), you must call this again after killing the window; otherwise,
the application window will not exist.


Climbing the GUI Learning Curve | 371
Free download pdf