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

(yzsuai) #1

From the perspective of the container window, the label is gridded to column 0 in the
current row number (a counter that starts at 0) and the entry is placed in column 1.
The upshot is that the grid system lays out all the labels and entries in a two-dimensional
table automatically, with both evenly sized rows and evenly sized columns large enough
to hold the largest item in each column.


That is, because widgets are arranged by both row and column when gridded, they align
properly in both dimensions. Although packed row frames can achieve the same effect
if labels are fixed width (as we learned in Chapter 8), grids directly reflect the structure
of tabular displays; this includes input forms, as well as larger tables in general. The
next section illustrates this difference in code.


Comparing grid and pack


Time for some compare-and-contrast: Example 9-19 implements the same sort of
colorized input form with both grid and pack, to make it easy to see the differences
between the two approaches.


Example 9-19. PP4E\Gui\Tour\Grid\grid2.py


"""
add equivalent pack window using row frames and fixed-width labels;
Labels and Entrys in packed column frames may not line up horizontally;
same length code, though enumerate built-in could trim 2 lines off grid;
"""


from tkinter import *
colors = ['red', 'green', 'orange', 'white', 'yellow', 'blue']


def gridbox(parent):
"grid by row/column numbers"
row = 0
for color in colors:
lab = Label(parent, text=color, relief=RIDGE, width=25)
ent = Entry(parent, bg=color, relief=SUNKEN, width=50)
lab.grid(row=row, column=0)
ent.grid(row=row, column=1)


Figure 9-29. The grid geometry manager in pseudoliving color


566 | Chapter 9: A tkinter Tour, Part 2

Free download pdf