Figure 8-43. tkinter GIF display
Example 8-42 works, but only for image types supported by the base tkinter toolkit.
To display other image formats, such as JPEG, we need to install PIL and use its re-
placement PhotoImage object. In terms of code, it’s simply a matter of adding one import
statement, as illustrated in Example 8-43.
Example 8-43. PP4E\Gui\PIL\viewer-pil.py
"""
show one image with PIL photo replacement object
handles many more image types; install PIL first: placed in Lib\site-packages
"""
import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage # <== use PIL replacement class
rest of code unchanged
imgdir = 'images'
imgfile = 'florida-2009-1.jpg' # does gif, jpg, png, tiff, etc.
if len(sys.argv) > 1:
imgfile = sys.argv[1]
imgpath = os.path.join(imgdir, imgfile)
win = Tk()
win.title(imgfile)
imgobj = PhotoImage(file=imgpath) # now JPEGs work!
Label(win, image=imgobj).pack()
494 | Chapter 8: A tkinter Tour, Part 1