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

(yzsuai) #1

def draw():
name, photo = random.choice(images)
lbl.config(text=name)
pix.config(image=photo)


root=Tk()
lbl = Label(root, text="none", bg='blue', fg='red')
pix = Button(root, text="Press me", command=draw, bg='white')
lbl.pack(fill=BOTH)
pix.pack(pady=10)
demoCheck.Demo(root, relief=SUNKEN, bd=2).pack(fill=BOTH)


files = glob(gifdir + "*.gif") # GIFs for now
images = [(x, PhotoImage(file=x)) for x in files] # load and hold
print(files)
root.mainloop()


This code uses a handful of built-in tools from the Python library:



  • The Python glob module we first met in Chapter 4 gives a list of all files ending
    in .gif in a directory; in other words, all GIF files stored there.

  • The Python random module is used to select a random GIF from files in the directory:
    random.choice picks and returns an item from a list at random.

  • To change the image displayed (and the GIF file’s name in a label at the top of the
    window), the script simply calls the widget config method with new option set-
    tings; changing on the fly like this changes the widget’s display dynamically.


Just for fun, this script also attaches an instance of the demoCheck check button demo
bar from Example 8-22, which in turn attaches an instance of the Quitter button we
wrote earlier in Example 8-7. This is an artificial example, of course, but it again dem-
onstrates the power of component class attachment at work.


Notice how this script builds and holds on to all images in its images list. The list
comprehension here applies a PhotoImage constructor call to every .gif file in the photo
directory, producing a list of (filename, imageobject) tuples that is saved in a global
variable (a map call using a one-argument lambda function could do the same). Remem-
ber, this guarantees that image objects won’t be garbage collected as long as the pro-
gram is running. Figure 8-40 shows this script in action on Windows.


Although it may not be obvious in this grayscale book, the name of the GIF file being
displayed is shown in red text in the blue label at the top of this window. This program’s
window grows and shrinks automatically when larger and smaller GIF files are dis-
played; Figure 8-41 shows it randomly picking a taller photo globbed from the image
directory.


488 | Chapter 8: A tkinter Tour, Part 1

Free download pdf