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

(yzsuai) #1

You can also avoid the DOS pop up on Windows by running the program with the
pythonw.exe executable, not python.exe (in fact, .pyw files are simply registered to be
opened by pythonw). On Linux, the .pyw doesn’t hurt, but it isn’t necessary; there is no
notion of a streams pop up on Unix-like machines. On the other hand, if your GUI
scripts might run on Windows in the future, adding an extra “w” at the end of their
names now might save porting effort later. In this book, .py filenames are still sometimes
used to pop up console windows for viewing printed messages on Windows.


tkinter Coding Alternatives


As you might expect, there are a variety of ways to code the gui1 example. For instance,
if you want to make all your tkinter imports more explicit in your script, grab the whole
module and prefix all of its names with the module’s name, as in Example 7-3.


Example 7-3. PP4E\Gui\Intro\gui1b.py—import versus from


import tkinter
widget = tkinter.Label(None, text='Hello GUI world!')
widget.pack()
widget.mainloop()


That will probably get tedious in realistic examples, though—tkinter exports dozens
of widget classes and constants that show up all over Python GUI scripts. In fact, it is
usually easier to use a * to import everything from the tkinter module by name in one
shot. This is demonstrated in Example 7-4.


Example 7-4. PP4E\Gui\Intro\gui1c.py—roots, sides, pack in place


from tkinter import *
root = Tk()
Label(root, text='Hello GUI world!').pack(side=TOP)
root.mainloop()


The tkinter module goes out of its way to export only what we really need, so it’s one
of the few for which the * import form is relatively safe to apply.‖ The TOP constant in
the pack call here, for instance, is one of those many names exported by the tkinter
module. It’s simply a variable name (TOP="top") preassigned in constants, a module
automatically loaded by tkinter.


When widgets are packed, we can specify which side of their parent they should be
attached to—TOP, BOTTOM, LEFT, or RIGHT. If no side option is sent to pack (as in prior
examples), a widget is attached to its parent’s TOP by default. In general, larger tkinter
GUIs can be constructed as sets of rectangles, attached to the appropriate sides of other,


‖If you study the main tkinter file in the Python source library (currently, Lib\tkinter__init__.py), you’ll notice
that top-level module names not meant for export start with a single underscore. Python never copies over
such names when a module is accessed with the * form of the from statement. The constants module is today
constants.py in the same module package directory, though this can change (and has) over time.


372 | Chapter 7: Graphical User Interfaces

Free download pdf