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

(yzsuai) #1

from tkinter import *
from grid2 import gridbox, packbox


root = Tk()
gridbox(root)
packbox(root)
Button(root, text='Quit', command=root.quit).pack()
mainloop()


This script passes the same parent (the top-level window) to each function in an effort
to make both forms appear in one window. It also utterly hangs the Python process on
my machine, without ever showing any windows at all (on some versions of Windows,
I’ve had to resort to Ctrl-Alt-Delete to kill it; on others, the Command Prompt shell
window must sometimes be restarted altogether).


Geometry manager combinations can be subtle until you get the hang of this. To make
this example work, for instance, we simply need to isolate the grid box in a parent
container all its own to keep it away from the packing going on in the root window—
as in the following bold alternative code:


root = Tk()
frm = Frame(root)
frm.pack() # this works
gridbox(frm) # gridbox must have its own parent in which to grid
packbox(root)
Button(root, text='Quit', command=root.quit).pack()
mainloop()

Again, today you must either pack or grid within one parent, but not both. It’s possible
that this restriction may be lifted in the future, but it’s been a long-lived constraint, and
it seems unlikely to be removed, given the disparity in the two window manager
schemes; try your Python to be sure.


Making Gridded Widgets Expandable


And now, some practical bits: the grids we’ve seen so far are fixed in size; they do not
grow when the enclosing window is resized by a user. Example 9-22 implements an
unreasonably patriotic input form with both grid and pack again, but adds the config-
uration steps needed to make all widgets in both windows expand along with their
window on a resize.


Example 9-22. PP4E\Gui\Tour\Grid\grid3.py


"add a label on the top and form resizing"


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


def gridbox(root):
Label(root, text='Grid').grid(columnspan=2)


570 | Chapter 9: A tkinter Tour, Part 2

Free download pdf