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

(yzsuai) #1

Figure 9-33. grid and pack windows resized


As coded, shrinking the pack window clips items packed last; shrinking the grid win-
dow shrinks all labels and entries together unlike grid2’s default behavior (try this on
your own).


Resizing in grids


Now that I’ve shown you what these windows do, I need to explain how they do it.
We learned in Chapter 7 how to make widgets expand with pack: we use expand and
fill options to increase space allocations and stretch into them, respectively. To make
expansion work for widgets arranged by grid, we need to use different protocols. Rows
and columns must be marked with a weight to make them expandable, and widgets
must also be made sticky so that they are stretched within their allocated grid cell:


Heavy rows and columns
With pack, we make each row expandable by making the corresponding Frame
expandable, with expand=YES and fill=BOTH. Gridders must be a bit more specific:
to get full expandability, call the grid container’s rowconfigure method for each
row and its columnconfigure for each column. To both methods, pass a weight
option with a value greater than zero to enable rows and columns to expand.
Weight defaults to zero (which means no expansion), and the grid container in this
script is just the top-level window. Using different weights for different rows and
columns makes them grow at proportionally different rates.


Sticky widgets
With pack, we use fill options to stretch widgets to fill their allocated space hor-
izontally or vertically, and anchor options to position widgets within their allocated


572 | Chapter 9: A tkinter Tour, Part 2

Free download pdf