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

(yzsuai) #1

Other GUI toolkits for Python have pros and cons of their own, discussed later in this
book. For example, some exchange code simplicity for richer widget sets. wxPython,
for example, is much more feature-rich, but it’s also much more complicated to use.
By and large, though, other toolkits are variations on a theme—once you’ve learned
one GUI toolkit, others are easy to pick up. Because of that, we’ll focus on learning one
toolkit in its entirety in this book instead of sampling many partially.


Although they are free to employ network access at will, programs written with tradi-
tional GUIs like tkinter generally run on a single, self-contained machine. Some con-
sider web pages to be a kind of GUI as well, but you’ll have to read the next and final
section of this chapter to judge that for yourself.


For a Good Time...
There’s much more to the tkinter toolkit than we’ve touched on in this preview, of
course, and we’ll study it in depth in this book. As another quick example to hint at
what’s possible, though, the following script, fungui.py, uses the Python random module
to pick from a list, makes new independent windows with Toplevel, and uses the tkinter
after callback to loop by scheduling methods to run again after a number of
milliseconds:
from tkinter import *
import random
fontsize = 30
colors = ['red', 'green', 'blue', 'yellow', 'orange', 'cyan', 'purple']
def onSpam():
popup = Toplevel()
color = random.choice(colors)
Label(popup, text='Popup', bg='black', fg=color).pack(fill=BOTH)
mainLabel.config(fg=color)
def onFlip():
mainLabel.config(fg=random.choice(colors))
main.after(250, onFlip)
def onGrow():
global fontsize
fontsize += 5
mainLabel.config(font=('arial', fontsize, 'italic'))
main.after(100, onGrow)
main = Tk()
mainLabel = Label(main, text='Fun Gui!', relief=RAISED)
mainLabel.config(font=('arial', fontsize, 'italic'), fg='cyan',bg='navy')
mainLabel.pack(side=TOP, expand=YES, fill=BOTH)
Button(main, text='spam', command=onSpam).pack(fill=X)
Button(main, text='flip', command=onFlip).pack(fill=X)
Button(main, text='grow', command=onGrow).pack(fill=X)
main.mainloop()
Run this on your own to see how it works. It creates a main window with a custom
label and three buttons—one button pops up a new window with a randomly colored
label, and the other two kick off potentially independent timer loops, one of which

Step 5: Adding a GUI | 51
Free download pdf