And finally, Figure 8-42 captures this script’s GUI displaying one of the wider GIFs,
selected completely at random from the photo file directory.‡
Figure 8-42. buttonpics gets political
While we’re playing, let’s recode this script as a class in case we ever want to attach or
customize it later (it could happen, especially in more realistic programs). It’s mostly
a matter of indenting and adding self before global variable names, as shown in
Example 8-41.
Example 8-41. PP4E\Gui\Tour\buttonpics.py
from tkinter import * # get base widget set
from glob import glob # filename expansion list
import demoCheck # attach check button example to me
import random # pick a picture at random
gifdir = '../gifs/' # default dir to load GIF files
class ButtonPicsDemo(Frame):
def init(self, gifdir=gifdir, parent=None):
Frame.init(self, parent)
self.pack()
self.lbl = Label(self, text="none", bg='blue', fg='red')
self.pix = Button(self, text="Press me", command=self.draw, bg='white')
self.lbl.pack(fill=BOTH)
self.pix.pack(pady=10)
demoCheck.Demo(self, relief=SUNKEN, bd=2).pack(fill=BOTH)
files = glob(gifdir + "*.gif")
self.images = [(x, PhotoImage(file=x)) for x in files]
print(files)
def draw(self):
name, photo = random.choice(self.images)
‡ This particular image is not my creation; it appeared as a banner ad on developer-related websites such as
Slashdot when the book Learning Python was first published in 1999. It generated enough of a backlash from
Perl zealots that O’Reilly eventually pulled the ad altogether. Which may be why, of course, it later appeared
in this book.
490 | Chapter 8: A tkinter Tour, Part 1