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

(yzsuai) #1

import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage # <== required for JPEGs and others


imgdir = 'images'
if len(sys.argv) > 1: imgdir = sys.argv[1]
imgfiles = os.listdir(imgdir) # does not include directory prefix


main = Tk()
main.title('Viewer')
quit = Button(main, text='Quit all', command=main.quit, font=('courier', 25))
quit.pack()
savephotos = []


for imgfile in imgfiles:
imgpath = os.path.join(imgdir, imgfile)
win = Toplevel()
win.title(imgfile)
try:
imgobj = PhotoImage(file=imgpath)
Label(win, image=imgobj).pack()
print(imgpath, imgobj.width(), imgobj.height()) # size in pixels
savephotos.append(imgobj) # keep a reference
except:
errmsg = 'skipping %s\n%s' % (imgfile, sys.exc_info()[1])
Label(win, text=errmsg).pack()


main.mainloop()


Run this code on your own to see the windows it generates. If you do, you’ll get one
main window with a Quit button to kill all the windows at once, plus as many pop-up
image view windows as there are images in the directory. This is convenient for a quick
look, but not exactly the epitome of user friendliness for large directories! The sample
images directory used for testing, for instance, has 59 images, yielding 60 pop-up win-
dows; those created by your digital camera may have many more. To do better, let’s
move on to the next section.


Creating Image Thumbnails with PIL


As mentioned, PIL does more than display images in a GUI; it also comes with tools
for resizing, converting, and more. One of the many useful tools it provides is the ability
to generate small, “thumbnail” images from originals. Such thumbnails may be dis-
played in a web page or selection GUI to allow the user to open full-size images on
demand.


Example 8-45 is a concrete implementation of this idea—it generates thumbnail images
using PIL and displays them on buttons which open the corresponding original image
when clicked. The net effect is much like the file explorer GUIs that are now standard
on modern operating systems, but by coding this in Python, we’re able to control its
behavior and to reuse and customize its code in our own applications. In fact, we’ll


496 | Chapter 8: A tkinter Tour, Part 1

Free download pdf