with code of this form:
from tkinter import *
from PIL import ImageTk
photoimg = ImageTk.PhotoImage(file=imgdir + "spam.jpg")
Button(image=photoimg).pack()
or with the more verbose equivalent, which comes in handy if you will perform image
processing in addition to image display:
from tkinter import *
from PIL import Image, ImageTk
imageobj = Image.open(imgdir + "spam.jpeg")
photoimg = ImageTk.PhotoImage(imageobj)
Button(image=photoimg).pack()
In fact, to use PIL for image display, all you really need to do is install it and add a single
from statement to your code to get its replacement PhotoImage object after loading the
original from tkinter. The rest of your code remains unchanged but will be able to
display JPEG, PNG, and other image types:
from tkinter import *
from PIL.ImageTk import PhotoImage # <== add this line
imgobj = PhotoImage(file=imgdir + "spam.png")
Button(image=imgobj).pack()
PIL installation details vary per platform; on Windows, it is just a matter of down-
loading and running a self-installer. PIL code winds up in the Python install directory’s
Lib\site-packages; because this is automatically added to the module import search
path, no path configuration is required to use PIL. Simply run the installer and import
the PIL package’s modules. On other platforms, you might untar or unZIP a fetched
source code archive and add PIL directories to the front of your PYTHONPATH setting; see
the PIL system’s website for more details. (In fact, I am using a pre-release version of
PIL for Python 3.1 in this edition; it should be officially released by the time you read
these words.)
There is much more to PIL than we have space to cover here. For instance, it also
provides image conversion, resizing, and transformation tools, some of which can be
run as command-line programs that have nothing to do with GUIs directly. Especially
for tkinter-based programs that display or process images, PIL will likely become a
standard component in your software tool set.
See http://www.pythonware.com for more information, as well as online PIL and tkinter
documentation sets. To help get you started, though, we’ll close out this chapter with
a handful of real scripts that use PIL for image display and processing.
492 | Chapter 8: A tkinter Tour, Part 1