| I l@ve RuBoard |
|
7.2 Configuring Widget AppearanceSo far, all the buttons and labels in examples have been rendered with a default look-and-feel that is standard for the underlying platform. That usually means gray on Windows, with my machine's color scheme. Tkinter widgets can be made to look arbitrarily different, though, using a handful of widget and packer options. Because I generally can't resist the temptation to customize widgets in examples, I want to cover this topic early on the tour. Example 7-1 introduces some of the configuration options available in Tkinter. Example 7-1. PP2E\Gui\Tour\config-label.pyfrom Tkinter import *
root = Tk()
labelfont = ('times', 20, 'bold') # family, size, style
widget = Label(root, text='Hello config world')
widget.config(bg='black', fg='yellow') # yellow text on black label
widget.config(font=labelfont) # use a larger font
widget.config(height=3, width=20) # initial size: lines,chars
widget.pack(expand=YES, fill=BOTH)
root.mainloop()
Remember, we can call a widget's config method to reset its options at any time, instead of passing them all to the object's constructor. Here, we use it to set options that produce the window in Figure 7-1. Figure 7-1. A custom label appearance![]() This may not be completely obvious unless you run this script on a real computer (alas, I can't show it in color here), but the label's text here shows up in yellow on a black background, and with a font that's very different from what we've seen so far. In fact, this script customizes the label in number of ways:
In this script, the net effect of all these settings is that this label looks radically different then 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. Tkinter provides additional ways to customize appearance, not used by this script:
To illustrate some of these extra settings, Example 7-2 configures the custom button captured in Figure 7-2 and changes the mouse pointer when above it. Example 7-2. PP2E\Gui\Tour\config-button.pyfrom 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()
Figure 7-2. Config button at work![]() To see the effects generated by these two script's settings, try out a few changes on your computer. Most widgets can be given a custom appearance in the same way, and we'll see such options used repeatedly in this text. We'll also meet operational configurations, such as focus (for focusing input), and more. In fact, widgets can have dozens of options; most have reasonable defaults that produce a native look-and-feel on each windowing platform, and this is one reason for Tkinter's simplicity. But Tkinter lets you build more custom displays when you want to. |
| I l@ve RuBoard |
|