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

(yzsuai) #1
elsewhere), and normal (large enough for window content). The methods lift and
lower raise and lower a window with respect to its siblings (lift is the Tk raise
command, but avoids a Python reserved word). See the alarm scripts near the end
of Chapter 9 for usage.

Menus
Each top-level window can have its own window menus too; both the Tk and the
Toplevel widgets have a menu option used to associate a horizontal menu bar of
pull-down option lists. This menu bar looks as it should on each platform on which
your scripts are run. We’ll explore menus early in Chapter 9.


Most top-level window-manager-related methods can also be named with a “wm_” at
the front; for instance, state and protocol can also be called wm_state and wm_protocol.


Notice that the script in Example 8-3 passes its Toplevel constructor calls an explicit
parent widget—the Tk root window (that is, Toplevel(root)). Toplevels can be asso-
ciated with a parent just as other widgets can, even though they are not visually em-
bedded in their parents. I coded the script this way to avoid what seems like an odd
feature; if coded instead like this:


win = Toplevel() # new window

and if no Tk root yet exists, this call actually generates a default Tk root window to serve
as the Toplevel’s parent, just like any other widget call without a parent argument. The
problem is that this makes the position of the following line crucial:


root = Tk() # explicit root

If this line shows up above the Toplevel calls, it creates the single root window as
expected. But if you move this line below the Toplevel calls, tkinter creates a default
Tk root window that is different from the one created by the script’s explicit Tk call. You
wind up with two Tk roots just as in Example 8-4. Move the Tk call below the
Toplevel calls and rerun it to see what I mean. You’ll get a fourth window that is com-
pletely empty! As a rule of thumb, to avoid such oddities, make your Tk root windows
early on and make them explicit.


All of the top-level protocol interfaces are available only on top-level window widgets,
but you can often access them by going through other widgets’ master attributes—links
to the widget parents. For example, to set the title of a window in which a frame is
contained, say something like this:


theframe.master.title('Spam demo') # master is the container window

Naturally, you should do so only if you’re sure that the frame will be used in only one
kind of window. General-purpose attachable components coded as classes, for in-
stance, should leave window property settings to their client applications.


Top-level widgets have additional tools, some of which we may not meet in this book.
For instance, under Unix window managers, you can also set the name used on the
window’s icon (iconname). Because some icon options may be useful when scripts run


Top-Level Windows | 425
Free download pdf