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

(yzsuai) #1

ent.insert(0, 'grid')
row += 1


def packbox(parent):
"row frames with fixed-width labels"
for color in colors:
row = Frame(parent)
lab = Label(row, text=color, relief=RIDGE, width=25)
ent = Entry(row, bg=color, relief=SUNKEN, width=50)
row.pack(side=TOP)
lab.pack(side=LEFT)
ent.pack(side=RIGHT)
ent.insert(0, 'pack')


if name == 'main':
root = Tk()
gridbox(Toplevel())
packbox(Toplevel())
Button(root, text='Quit', command=root.quit).pack()
mainloop()


The pack version here uses row frames with fixed-width labels (again, column frames
can skew rows). The basic label and entry widgets are created the same way by these
two functions, but they are arranged in very different ways:



  • With pack, we use side options to attach labels and rows on the left and right, and
    create a Frame for each row (itself attached to the parent’s current top).

  • With grid, we instead assign each widget a row and column position in the implied
    tabular grid of the parent, using options of the same name.


As we’ve learned, with pack, the packing order can matter, too: a widget gets an entire
side of the remaining space (mostly irrelevant here), and items packed first are clipped
last (labels and topmost rows disappear last here). The grid alternative achieves the
same clipping effect by virtue of grid behavior. Running the script makes the windows
in Figure 9-30—one window for each scheme.


If you study this example closely, you’ll find that the difference in the amount of code
required for each layout scheme is roughly a wash, at least in this simple form. The
pack scheme must create a Frame per row, but the grid scheme must keep track of the
current row number.


In fact, both schemes require the same number of code lines as shown, though to be
fair we could shave one line from each by packing or gridding the label immediately,
and could shave two more lines from the grid layout by using the built-in enumerate
function to avoid manual counting. Here’s a minimalist’s version of the grid box func-
tion for reference:


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

Grids | 567
Free download pdf