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

(yzsuai) #1

Displaying Other Image Types with PIL


In our earlier image examples, we attached widgets to buttons and canvases, but the
standard tkinter toolkit allows images to be added to a variety of widget types, including
simple labels, text, and menu entries. Example 8-42, for instance, uses unadorned
tkinter to display a single image by attaching it to a label, in the main application win-
dow. The example assumes that images are stored in an images subdirectory, and it
allows the image filename to be passed in as a command-line argument (it defaults to
spam.gif if no argument is passed). It also joins file and directory names more portably
with os.path.join, and it prints the image’s height and width in pixels to the standard
output stream, just to give extra information.


Example 8-42. PP4E\Gui\PIL\viewer-tk.py


"""
show one image with standard tkinter photo object;
as is this handles GIF files, but not JPEG images; image filename listed in
command line, or default; use a Canvas instead of Label for scrolling, etc.
"""


import os, sys
from tkinter import * # use standard tkinter photo object


GIF works, but JPEG requires PIL


imgdir = 'images'
imgfile = 'london-2010.gif'
if len(sys.argv) > 1: # cmdline argument given?
imgfile = sys.argv[1]
imgpath = os.path.join(imgdir, imgfile)


win = Tk()
win.title(imgfile)
imgobj = PhotoImage(file=imgpath) # display photo on a Label
Label(win, image=imgobj).pack()
print(imgobj.width(), imgobj.height()) # show size in pixels before destroyed
win.mainloop()


Figure 8-43 captures this script’s display on Windows 7, showing the default GIF image
file. Run this from the system console with a filename as a command-line argument to
view other files in the images subdirectory (e.g., python viewer_tk.py filename.gif).


Viewing and Processing Images with PIL | 493
Free download pdf