Example 9-24. PP4E\Gui\Tour\Grid\grid5.py
2D table of input fields, default Tk root window
from tkinter import *
rows = []
for i in range(5):
cols = []
for j in range(4):
ent = Entry(relief=RIDGE)
ent.grid(row=i, column=j, sticky=NSEW)
ent.insert(END, '%d.%d' % (i, j))
cols.append(ent)
rows.append(cols)
def onPress():
for row in rows:
for col in row:
print(col.get(), end=' ')
print()
Button(text='Fetch', command=onPress).grid()
mainloop()
When run, this script creates the window in Figure 9-35 and saves away all the grid’s
entry field widgets in a two-dimensional list of lists. When its Fetch button is pressed,
the script steps through the saved list of lists of entry widgets, to fetch and display all
the current values in the grid. Here is the output of two Fetch presses—one before I
made input field changes, and one after:
C:\...\PP4E\Gui\Tour\Grid> python grid5.py
0.0 0.1 0.2 0.3
1.0 1.1 1.2 1.3
2.0 2.1 2.2 2.3
3.0 3.1 3.2 3.3
4.0 4.1 4.2 4.3
0.0 0.1 0.2 42
1.0 1.1 1.2 43
2.0 2.1 2.2 44
3.0 3.1 3.2 45
4.0 4.1 4.2 46
Now that we know how to build and step through arrays of input fields, let’s add a few
more useful buttons. Example 9-25 adds another row to display column sums and adds
buttons to clear all fields to zero and calculate column sums.
Example 9-25. PP4E\Gui\Tour\Grid\grid5b.py
add column sums, clearing
from tkinter import *
numrow, numcol = 5, 4
Grids | 575