"""
create thumbs in memory but don't cache to files
"""
thumbs = []
for imgfile in os.listdir(imgdir):
imgpath = os.path.join(imgdir, imgfile)
try:
imgobj = Image.open(imgpath) # make new thumb
imgobj.thumbnail(size)
thumbs.append((imgfile, imgobj))
except:
print("Skipping: ", imgpath)
return thumbs
if name == 'main':
imgdir = (len(sys.argv) > 1 and sys.argv[1]) or 'images'
viewer_thumbs.makeThumbs = makeThumbs
main, save = viewer_thumbs.viewer(imgdir, kind=Tk)
main.mainloop()
Layout options: Gridding
The next variations on our viewer are purely cosmetic, but they illustrate tkinter layout
concepts. If you look at Figure 8-45 long enough, you’ll notice that its layout of thumb-
nails is not as uniform as it could be. Individual rows are fairly coherent because the
GUI is laid out by row frames, but columns can be misaligned badly due to differences
in image shape. Different packing options don’t seem to help (and can make matters
even more askew—try it), and arranging by column frames would just shift the problem
to another dimension. For larger collections, it could become difficult to locate and
open specific images.
With just a little extra work, we can achieve a more uniform layout by either laying out
the thumbnails in a grid, or using uniform fixed-size buttons. Example 8-47 positions
buttons in a row/column grid by using the tkinter grid geometry manager—a topic we
will explore in more detail in the next chapter, so like the canvas, you should consider
some of this code to be a preview and segue, too. In short, grid arranges its contents
by row and column; we’ll learn all about the stickiness of the Quit button here in
Chapter 9.
Example 8-47. PP4E\Gui\PIL\viewer-thumbs-grid.py
"""
same as viewer_thumbs, but uses the grid geometry manager to try to achieve
a more uniform layout; can generally achieve the same with frames and pack
if buttons are all fixed and uniform in size;
"""
import sys, math
from tkinter import *
from PIL.ImageTk import PhotoImage
from viewer_thumbs import makeThumbs, ViewOne
Viewing and Processing Images with PIL | 501