Much of Example 8-45’s code should be straightforward by now. It lays out thumbnail
buttons in row frames, much like prior examples (see the input forms layout alternatives
earlier in this chapter). Most of the PIL-specific code in this example is in the make
Thumbs function. It opens, creates, and saves the thumbnail image, unless one has al-
ready been saved (i.e., cached) to a local file. As coded, thumbnail images are saved in
the same image format as the original full-size photo.
We also use the PIL ANTIALIAS filter—the best quality for down-sampling (shrinking);
this does a better job on low-resolution GIFs. Thumbnail generation is essentially just
an in-place resize that preserves the original aspect ratio. Because there is more to this
story than we can cover here, though, I’ll defer to PIL and its documentation for more
details on that package’s API.
We’ll revisit thumbnail creation again briefly in the next chapter to create toolbar but-
tons. Before we move on, though, three variations on the thumbnail viewer are worth
quick consideration—the first underscores performance concepts and the others have
to do with improving on the arguably odd layout of Figure 8-45.
Performance: Saving thumbnail files
As is, the viewer saves the generated thumbnail image in a file, so it can be loaded
quickly the next time the script is run. This isn’t strictly required—Example 8-46, for
instance, customizes the thumbnail generation function to generate the thumbnail im-
ages in memory, but never save them.
There is no noticeable speed difference for very small image collections. If you run these
alternatives on larger image collections, though, you’ll notice that the original version
in Example 8-45 gains a big performance advantage by saving and loading the thumb-
nails to files. On one test with many large image files on my machine (some 320 images
from a digital camera memory stick and an admittedly underpowered laptop), the
original version opens the GUI in roughly just 5 seconds after its initial run to cache
thumbnails, compared to as much as 1 minute and 20 seconds for Example 8-46: a
factor of 16 slower. For thumbnails, loading from files is much quicker than
recalculation.
Example 8-46. PP4E\Gui\PIL\viewer-thumbs-nosave.py
"""
same, but make thumb images in memory without saving to or loading from files:
seems just as fast for small directories, but saving to files makes startup much
quicker for large image collections; saving may be needed in some apps (web pages)
"""
import os, sys
from PIL import Image
from tkinter import Tk
import viewer_thumbs
def makeThumbs(imgdir, size=(100, 100), subdir='thumbs'):
500 | Chapter 8: A tkinter Tour, Part 1