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

(yzsuai) #1

Similarly, displays that include scroll bars normally pack them before the items they
scroll (e.g., text, lists) so that the scroll bars remain as the window shrinks.


Attaching Widgets to Frames


In larger terms, the critical innovation in this example is its use of frames: Frame widgets
are just containers for other widgets, and so give rise to the notion of GUIs as widget
hierarchies, or trees. Here, win serves as an enclosing window for the other three
widgets. In general, though, by attaching widgets to frames, and frames to other frames,
we can build up arbitrary GUI layouts. Simply divide the user interface into a set of
increasingly smaller rectangles, implement each as a tkinter Frame, and attach basic
widgets to the frame in the desired screen position.


In this script, when you specify win in the first argument to the Label and Button con-
structors, tkinter attaches them to the Frame (they become children of the win parent).
win itself is attached to the default top-level window, since we didn’t pass a parent to
the Frame constructor. When we ask win to run itself (by calling mainloop), tkinter draws
all the widgets in the tree we’ve built.


The three child widgets also provide pack options now: the side arguments tell which
part of the containing frame (i.e., win) to attach the new widget to. The label hooks
onto the top, and the buttons attach to the sides. TOP, LEFT, and RIGHT are all preassigned
string variables imported from tkinter. Arranging widgets is a bit subtler than simply
giving a side, though, but we need to take a quick detour into packer geometry man-
agement details to see why.


Layout: Packing Order and Side Attachments


When a widget tree is displayed, child widgets appear inside their parents and are
arranged according to their order of packing and their packing options. Because of this,
the order in which widgets are packed not only gives their clipping order, but also
determines how their side settings play out in the generated display.


Here’s how the packer’s layout system works:



  1. The packer starts out with an available space cavity that includes the entire parent
    container (e.g., the whole Frame or top-level window).

  2. As each widget is packed on a side, that widget is given the entire requested side
    in the remaining space cavity, and the space cavity is shrunk.

  3. Later pack requests are given an entire side of what is left, after earlier pack requests
    have shrunk the cavity.

  4. After widgets are given cavity space, expand divides any space left, and fill and
    anchor stretch and position widgets within their assigned space.


Adding Multiple Widgets| 397
Free download pdf