Using images in toolbars, too
As shown in Figure 9-11, it’s easy to use images for menu items. Although not used in
Example 9-8, toolbar items can be pictures too, just like the Image menu’s items—
simply associate small images with toolbar frame buttons, just as we did in the image
button examples we wrote in the last part of Chapter 8. If you create toolbar images
manually ahead of time, it’s simple to associate them with buttons as we’ve learned. In
fact, it’s not much more work to build them dynamically—the PIL-based thumbnail
image construction skills we developed in the prior chapter might come in handy in
this context as well.
To illustrate, make sure you’ve installed the PIL extension, and replace the toolbar
construction method of Example 9-8 with the following (I’ve done this in file menu-
Demo2.py in the examples distribution so you can run and experiment on your own):
# resize toolbar images on the fly with PIL
def makeToolBar(self, size=(40, 40)):
from PIL.ImageTk import PhotoImage, Image # if jpegs or make new thumbs
imgdir = r'../PIL/images/'
toolbar = Frame(self, cursor='hand2', relief=SUNKEN, bd=2)
toolbar.pack(side=BOTTOM, fill=X)
photos = 'ora-lp4e-big.jpg', 'PythonPoweredAnim.gif', 'python_conf_ora.gif'
self.toolPhotoObjs = []
for file in photos:
imgobj = Image.open(imgdir + file) # make new thumb
imgobj.thumbnail(size, Image.ANTIALIAS) # best downsize filter
img = PhotoImage(imgobj)
btn = Button(toolbar, image=img, command=self.greeting)
btn.config(relief=RAISED, bd=2)
btn.config(width=size[0], height=size[1])
btn.pack(side=LEFT)
self.toolPhotoObjs.append((img, imgobj)) # keep a reference
Button(toolbar, text='Quit', command=self.quit).pack(side=RIGHT, fill=Y)
When run, this alternative creates the window captured in Figure 9-12—the three im-
age options available in the Image menu at the top of the window are now also buttons
in the toolbar at the bottom, along with a simple text button for quitting on the right.
As before, the cursor becomes a hand over the toolbar.
You don’t need PIL at all if you’re willing to use GIF or supported bitmap images that
you create by hand manually—simply load by filename using the standard tkinter
photo object, as shown by the following alternative coding for the toolbar construction
method (this is file menuDemo3.py in the examples distribution if you’re keeping
scope):
# use unresized gifs with standard tkinter
def makeToolBar(self, size=(30, 30)):
imgdir = r'../gifs/'
toolbar = Frame(self, cursor='hand2', relief=SUNKEN, bd=2)
toolbar.pack(side=BOTTOM, fill=X)
520 | Chapter 9: A tkinter Tour, Part 2