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

(yzsuai) #1

we start using multiple top-level windows in Chapter 8, we’ll find that quit usually
closes all windows, but its relative destroy erases just one window.


Example 7-11. PP4E\Gui\Intro\gui2b.py


from tkinter import *
root = Tk()
Button(root, text='press', command=root.quit).pack(side=LEFT)
root.mainloop()


This version produces the window in Figure 7-6. Because we didn’t tell the button to
expand into all available space, it does not do so.


Figure 7-6. A button on the left


In both of the last two examples, pressing the button makes the GUI program exit. In
older tkinter code, you may sometimes see the string exit assigned to the command option
to make the GUI go away when pressed. This exploits a tool in the underlying Tk library
and is less Pythonic than sys.exit or root.quit.


Widget Resizing Revisited: Expansion


Even with a GUI this simple, there are many ways to lay out its appearance with tkinter’s
constraint-based pack geometry manager. For example, to center the button in its win-
dow, add an expand=YES option to the button’s pack method call in Example 7-11. The
line of changed code looks like this:


Button(root, text='press', command=root.quit).pack(side=LEFT, expand=YES)

This makes the packer allocate all available space to the button but does not stretch
the button to fill that space. The result is the window captured in Figure 7-7.


Figure 7-7. pack(side=LEFT, expand=YES)


If you want the button to be given all available space and to stretch to fill all of its
assigned space horizontally, add expand=YES and fill=X keyword arguments to the
pack call. This will create the scene in Figure 7-8.


380 | Chapter 7: Graphical User Interfaces

Free download pdf