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

(yzsuai) #1

Layout and expansion
Finally, the label is made generally expandable and stretched by setting the pack
expand and fill options we met in the last chapter; the label grows as the window
does. If you maximize this window, its black background fills the whole screen and
the yellow message is centered in the middle; try it.


In this script, the net effect of all these settings is that this label looks radically different
from the ones we’ve been making so far. It no longer follows the Windows standard
look-and-feel, but such conformance isn’t always important. For reference, tkinter
provides additional ways to customize appearance that are not used by this script, but
which may appear in others:


Border and relief
A bd= N widget option can be used to set border width, and a relief= S option can
specify a border style; S can be FLAT, SUNKEN, RAISED, GROOVE, SOLID, or RIDGE—all
constants exported by the tkinter module.


Cursor
A cursor option can be given to change the appearance of the mouse pointer when
it moves over the widget. For instance, cursor='gumby' changes the pointer to a
Gumby figure (the green kind). Other common cursor names used in this book
include watch, pencil, cross, and hand2.


State
Some widgets also support the notion of a state, which impacts their appearance.
For example, a state=DISABLED option will generally stipple (gray out) a widget on
screen and make it unresponsive; NORMAL does not. Some widgets support a
READONLY state as well, which displays normally but is unresponsive to changes.


Padding
Extra space can be added around many widgets (e.g., buttons, labels, and text)
with the padx= N and pady= N options. Interestingly, you can set these options both
in pack calls (where it adds empty space around the widget in general) and in a
widget object itself (where it makes the widget larger).


To illustrate some of these extra settings, Example 8-2 configures the custom button
captured in Figure 8-2 and changes the mouse pointer when it is positioned above it.


Example 8-2. PP4E\Gui\Tour\config-button.py


from tkinter import *
widget = Button(text='Spam', padx=10, pady=10)
widget.pack(padx=20, pady=20)
widget.config(cursor='gumby')
widget.config(bd=8, relief=RAISED)
widget.config(bg='dark green', fg='white')
widget.config(font=('helvetica', 20, 'underline italic'))
mainloop()


418 | Chapter 8: A tkinter Tour, Part 1

Free download pdf