Run this script with other filenames to view other images (try this on your own):
C:\...\PP4E\Gui\Tour> imgCanvas2.py ora-ppr-german.gif
And that’s all there is to it. In Chapter 9, we’ll see images show up again in the items
of a Menu, in the buttons of a window’s toolbar, in other Canvas examples, and in the
image-friendly Text widget. In later chapters, we’ll find them in an image slideshow
(PyView), in a paint program (PyDraw), on clocks (PyClock), in a generalized photo
viewer (PyPhoto), and so on. It’s easy to add graphics to GUIs in Python/tkinter.
Once you start using photos in earnest, though, you’re likely to run into two tricky bits
that I want to warn you about here:
Supported file types
At present, the standard tkinter PhotoImage widget supports only GIF, PPM, and
PGM graphic file formats, and BitmapImage supports X Windows-style .xbm bitmap
files. This may be expanded in future releases, and you can convert photos in other
formats to these supported formats ahead of time, of course. But as we’ll see later
in this chapter, it’s easy to support additional image types with the PIL open source
extension toolkit and its PhotoImage replacement.
Hold on to your images!
Unlike all other tkinter widgets, an image is utterly lost if the corresponding Python
image object is garbage collected. That means you must retain an explicit reference
to image objects for as long as your program needs them (e.g., assign them to a
long-lived variable name, object attribute, or data structure component). Python
does not automatically keep a reference to the image, even if it is linked to other
GUI components for display. Moreover, image destructor methods erase the image
from memory. We saw earlier that tkinter variables can behave oddly when re-
claimed, too (they may be unset), but the effect is much worse and more likely to
happen with images. This may change in future Python releases, though there are
good reasons for not retaining big image files in memory indefinitely; for now,
though, images are a “use it or lose it” widget.
Fun with Buttons and Pictures
I tried to come up with an image demo for this section that was both fun and useful. I
settled for the fun part. Example 8-40 displays a button that changes its image at ran-
dom each time it is pressed.
Example 8-40. PP4E\Gui\Tour\buttonpics-func.py
from tkinter import * # get base widget set
from glob import glob # filename expansion list
import demoCheck # attach checkbutton demo to me
import random # pick a picture at random
gifdir = '../gifs/' # where to look for GIF files
Images | 487