As mentioned in the preceding chapter, input forms are generally best arranged either
as grids or as row frames with fixed-width labels, so that labels and entry fields line up
horizontally as expected on all platforms (as we learned, column frames don’t work
reliably, because they may misalign rows). Although grids and row frames are roughly
the same amount of work, grids are useful if calculating maximum label width is in-
convenient. Moreover, grids also apply to tables more complex than forms.
As we’ll see, though, for input forms, grid doesn’t offer substantial code or complexity
savings compared to equivalent packer solutions, especially when things like resizabil-
ity are added to the GUI picture. In other words, the choice between the two layout
schemes is often largely one of style, not technology.
Grid Basics: Input Forms Revisited
Let’s start off with the basics; Example 9-18 lays out a table of Labels and Entry fields—
widgets we’ve already met. Here, though, they are arrayed on a grid.
Example 9-18. PP4E\Gui\Tour\Grid\grid1.py
from tkinter import *
colors = ['red', 'green', 'orange', 'white', 'yellow', 'blue']
r = 0
for c in colors:
Label(text=c, relief=RIDGE, width=25).grid(row=r, column=0)
Entry(bg=c, relief=SUNKEN, width=50).grid(row=r, column=1)
r += 1
mainloop()
Gridding assigns widgets to row and column numbers, which both begin at number 0;
tkinter uses these coordinates, along with widget size in general, to lay out the con-
tainer’s display automatically. This is similar to the packer, except that rows and col-
umns replace the packer’s notion of sides and packing order.
When run, this script creates the window shown in Figure 9-29, pictured with data
typed into a few of the input fields. Once again, this book won’t do justice to the colors
displayed on the right, so you’ll have to stretch your imagination a little (or run this
script on a computer of your own).
Despite its colors, this is really just a classic input form layout again, of the same kind
we met in the prior chapter. Labels on the left describe data to type into entry fields on
the right. Here, though, we achieve the layout with gridding instead of packed frames.
Just for fun, this script displays color names on the left and the entry field of the cor-
responding color on the right. It achieves its table-like layout with these lines:
Label(...).grid(row=r, column=0)
Entry(...).grid(row=r, column=1)
Grids | 565