if name == 'main':
import sys
root = Tk()
root.title('Summer Grid')
if len(sys.argv) != 3:
SumGrid(root).pack() # .grid() works here too
else:
rows, cols = eval(sys.argv[1]), eval(sys.argv[2])
SumGrid(root, rows, cols).pack()
mainloop()
Notice that this module’s SumGrid class is careful not to either grid or pack itself. In
order to be attachable to containers where other widgets are being gridded or packed,
it leaves its own geometry management ambiguous and requires callers to pack or grid
its instances. It’s OK for containers to pick either scheme for their own children because
they effectively seal off the pack-or-grid choice. But attachable component classes that
aim to be reused under both geometry managers cannot manage themselves because
they cannot predict their parent’s policy.
This is a fairly long example that doesn’t say much else about gridding or widgets in
general, so I’ll leave most of it as suggested reading and just show what it does. Fig-
ure 9-37 shows the initial window created by this script after changing the last column
and requesting a sum; make sure the directory containing the PP4E examples root is
on your module search path (e.g., PYTHONPATH) for the package import.
By default, the class makes the 5 × 5 grid here, but we can pass in other dimensions to
both the class constructor and the script’s command line. When you press the Load
button, you get the standard file selection dialog we met earlier on this tour
(Figure 9-38).
The datafile grid-data1.txt contains seven rows and six columns of data:
C:\...\PP4E\Gui\Tour\Grid> type grid5-data1.txt
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
Loading this file’s data into our GUI makes the dimensions of the grid change accord-
ingly—the class simply reruns its widget construction logic after erasing all the old entry
widgets with the grid_forget method. The grid_forget method unmaps gridded widg-
ets and so effectively erases them from the display. Also watch for the pack_forget
widget and window withdraw methods used in the after event “alarm” examples of the
next section for other ways to erase and redraw GUI components.
Once the GUI is erased and redrawn for the new data, Figure 9-39 captures the scene
after the file Load and a new Sum have been requested by the user in the GUI.
Grids | 579