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

(yzsuai) #1

  • Images: PhotoImage and BitmapImage objects

  • Widget and window configuration options

  • Dialogs, both standard and custom

  • Low-level event binding

  • tkinter linked variable objects

  • Using the Python Imaging Library (PIL) extension for other image types and
    operations


After this chapter, Chapter 9 concludes the two-part tour by presenting the remainder
of the tkinter library’s tool set: menus, text, canvases, animation, and more.


To make this tour interesting, I’ll also introduce a few notions of component reuse
along the way. For instance, some later examples will be built using components written
for prior examples. Although these two tour chapters introduce widget interfaces, this
book is also about Python programming in general; as we’ll see, tkinter programming
in Python can be much more than simply drawing circles and arrows.


Configuring Widget Appearance


So far, all the buttons and labels in examples have been rendered with a default look-
and-feel that is standard for the underlying platform. With my machine’s color scheme,
that usually means that they’re gray on Windows. 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 8-1 introduces some of the configuration
options available in tkinter.


Example 8-1. PP4E\Gui\Tour\config-label.py


from 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 all of them to the object’s constructor. Here, we use it to set options that
produce the window in Figure 8-1.


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 shows up in yellow on a black


416 | Chapter 8: A tkinter Tour, Part 1

Free download pdf