Figure 8-37. imgButton in action
PhotoImage and its cousin, BitmapImage, essentially load graphics files and allow those
graphics to be attached to other kinds of widgets. To open a picture file, pass its name
to the file attribute of these image objects. Though simple, attaching images to buttons
this way has many uses; in Chapter 9, for instance, we’ll use this basic idea to implement
toolbar buttons at the bottom of a window.
Canvas widgets—general drawing surfaces covered in more detail in the next chapter—
can display pictures too. Though this is a bit of a preview for the upcoming chapter,
basic canvas usage is straightforward enough to demonstrate here; Example 8-38 ren-
ders Figure 8-38 (shrunk here for display):
Example 8-38. PP4E\Gui\Tour\imgCanvas.py
gifdir = "../gifs/"
from tkinter import *
win = Tk()
img = PhotoImage(file=gifdir + "ora-lp4e.gif")
can = Canvas(win)
can.pack(fill=BOTH)
can.create_image(2, 2, image=img, anchor=NW) # x, y coordinates
win.mainloop()
Buttons are automatically sized to fit an associated photo, but canvases are not (because
you can add objects to a canvas later, as we’ll see in Chapter 9). To make a canvas fit
the picture, size it according to the width and height methods of image objects, as in
Example 8-39. This version will make the canvas smaller or larger than its default size
as needed, lets you pass in a photo file’s name on the command line, and can be used
as a simple image viewer utility. The visual effect of this script is captured in Figure 8-39.
Images | 485