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

(yzsuai) #1

For instance, if you recode the gui4 child widget creation logic like this:


Button(win, text='Hello', command=greeting).pack(side=LEFT)
Label(win, text='Hello container world').pack(side=TOP)
Button(win, text='Quit', command=win.quit).pack(side=RIGHT)

you will wind up with the very different display shown in Figure 7-15, even though
you’ve moved the label code only one line down in the source file (contrast with
Figure 7-12).


Figure 7-15. Packing the label second


Despite its side setting, the label does not get the entire top of the window now, and
you have to think in terms of shrinking cavities to understand why. Because the Hello
button is packed first, it is given the entire LEFT side of the Frame. Next, the label is given
the entire TOP side of what is left. Finally, the Quit button gets the RIGHT side of the
remainder—a rectangle to the right of the Hello button and under the label. When this
window shrinks, widgets are clipped in reverse order of their packing: the Quit button
disappears first, followed by the label.†


In the original version of this example (Figure 7-12), the label spans the entire top side
just because it is the first one packed, not because of its side option. In fact, if you look
at Figure 7-14 closely, you’ll see that it illustrates the same point—the label appeared
between the buttons, because they had already carved off the entire left and right sides.


The Packer’s Expand and Fill Revisited


Beyond the effects of packing order, the fill option we met earlier can be used to stretch
the widget to occupy all the space in the cavity side it has been given, and any cavity
space left after all packing is evenly allocated among widgets with the expand=YES we
saw before. For example, coding this way creates the window in Figure 7-16 (compare
this to Figure 7-15):


Button(win, text='Hello', command=greeting).pack(side=LEFT,fill=Y)
Label(win, text='Hello container world').pack(side=TOP)
Button(win, text='Quit', command=win.quit).pack(side=RIGHT, expand=YES, fill=X)

† Technically, the packing steps are just rerun again after a window resize. But since this means that there won’t
be enough space left for widgets packed last when the window shrinks, it is as if widgets packed first are
clipped last.


398 | Chapter 7: Graphical User Interfaces

Free download pdf