Section 9.9. Images

9.9. Images

In Tkinter, graphical images are displayed by creating independent PhotoImage or BitmapImage objects, and then attaching those image objects to other widgets via image attribute settings. Buttons, labels, canvases, text, and menus can display images by associating prebuilt image objects in this way. To illustrate, Example 9-36 throws a picture up on a button.

Example 9-36. PP3E\Gui\Tour\

 gifdir = "../gifs/" from Tkinter import * win = Tk( ) igm = PhotoImage(file=gifdir+"ora-pp.gif") Button(win, image=igm).pack( ) win.mainloop( ) 

I could try to come up with a simpler example, but it would be toughall this script does is make a Tkinter PhotoImage object for a GIF file stored in another directory, and associate it with a Button widget's image option. The result is captured in Figure 9-36.

Figure 9-36. 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. Canvas widgetsgeneral drawing surfaces discussed in more detail later in this tourcan display pictures too; Example 9-37 renders Figure 9-37.

Figure 9-37. An image on canvas

Example 9-37. PP3E\Gui\Tour\

 gifdir = "../gifs/" from Tkinter import * win = Tk( ) img = PhotoImage(file=gifdir+"ora-lp.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, as we'll see in Chapter 10). To make a canvas fit the picture, size it according to the width and height methods of image objects, as in Example 9-38. 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 9-38.

Figure 9-38. Sizing the canvas to match the photo

Example 9-38. PP3E\Gui\Tour\

 gifdir = "../gifs/" from sys import argv from Tkinter import * filename = (len(argv) > 1 and argv[1]) or 'ora-lp.gif'    # name on cmdline? win = Tk( ) img = PhotoImage(file=gifdir+filename) can = Canvas(win) can.pack(fill=BOTH) can.config(width=img.width(), height=img.height( ))        # size to img size can.create_image(2, 2, image=img, anchor=NW) win.mainloop( ) 

And that's all there is to it. In Chapter 10, we'll see images show up in a Menu, other Canvas examples, and the image-friendly Text widget. In later chapters, we'll find them in an image slideshow (PyView), in a paint program (PyDraw), on clocks (PyClock), and so on. It's easy to add graphics to GUIs in Python/Tkinter.

Once you start using photos in earnest, though, you're likely to run into two tricky bits which I want to warn you about here:

Supported file types

At present, the PhotoImage widget only supports GIF, PPM, and PGM graphic file formats, and BitmapImage supports X Windows-style .xbm bitmap files. This may be expanded in future releases, and you can convert photos in other formats to these supported formats, of course. But as we'll see later in this chapter, it's easy to support additional image types with the PIL open source extension toolkit.

Hold on to your photos

Unlike all other Tkinter widgets, an image is utterly lost if the corresponding Python image object is garbage collected. That means you must retain an explicit reference to image objects for as long as your program needs them (e.g., assign them to a long-lived variable name or data structure component). Python does not automatically keep a reference to the image, even if it is linked to other GUI components for display; moreover, image destructor methods erase the image from memory. We saw earlier that Tkinter variables can behave oddly when reclaimed too, but the effect is much worse and more likely to happen with images. This may change in future Python releases (though there are good reasons for not retaining big image files in memory indefinitely); for now, though, images are a "use it or lose it" widget.

9.9.1. Fun with Buttons and Pictures

I tried to come up with an image demo for this section that was both fun and useful. I settled for the fun part. Example 9-39 displays a button that changes its image at random each time it is pressed.

Example 9-39. PP3E\Gui\Tour\

 from Tkinter import *                # get base widget set from glob import glob                # filename expansion list import demoCheck                     # attach checkbutton demo to me import random                        # pick a picture at random gifdir = '../gifs/'                  # where to look for GIF files     def draw( ):     name, photo = random.choice(images)     lbl.config(text=name)     pix.config(image=photo) root=Tk( ) lbl = Label(root,  text="none", bg='blue', fg='red') pix = Button(root, text="Press me", command=draw, bg='white') lbl.pack(fill=BOTH) pix.pack(pady=10) demoCheck.Demo(root, relief=SUNKEN, bd=2).pack(fill=BOTH) files = glob(gifdir + "*.gif")                              # GIFs for now images = map((lambda x: (x, PhotoImage(file=x))), files)    # load and hold print files root.mainloop( ) 

This code uses a handful of built-in tools from the Python library:

  • The Python glob module we met earlier in the book gives a list of all files ending in .gif in a directory; in other words, all GIF files stored there.

  • The Python random module is used to select a random GIF from files in the directory: random.choice picks and returns an item from a list at random.

  • To change the image displayed (and the GIF file's name in a label at the top of the window), the script simply calls the widget config method with new option settings; changing on the fly like this changes the widget's display.

Just for fun, this script also attaches an instance of the demoCheck check button demo bar, which in turn attaches an instance of the Quitter button we wrote earlier. This is an artificial example, of course, but again it demonstrates the power of component class attachment at work.

Notice how this script builds and holds on to all images in its images list. The map here applies a PhotoImage constructor call to every .gif file in the photo directory, producing a list of (file,image) tuples that is saved in a global variable (a list comprehension [(x, PhotoImage(file=x)) for x in files] would do the same). Remember, this guarantees that image objects won't be garbage collected as long as the program is running. Figure 9-39 shows this script in action on Windows.

Figure 9-39. buttonpics in action

Although it may not be obvious in this grayscale book, the name of the GIF file being displayed is shown in red text in the blue label at the top of this window. This program's window grows and shrinks automatically when larger and smaller GIF files are displayed; Figure 9-40 shows it randomly picking a taller photo globbed from the image directory.

Figure 9-40. buttonpics showing a taller photo

And finally, Figure 9-41 captures this script's GUI displaying one of the wider GIFs, selected completely at random from the photo file directory.[*]

[*] This particular image appeared as a banner ad on developer-related web sites such as
when the book Learning Python was first published. It generated enough of a backlash from Perl zealots that O'Reilly eventually pulled the ad altogether. Which is why, of course, it appears in this book.

Figure 9-41. buttonpics gets political

While we're playing, let's recode this script as a class in case we ever want to attach or customize it later (it could happen). It's mostly a matter of indenting and adding self before global variable names, as shown in Example 9-40.

Example 9-40. PP3E\Gui\Tour\

 from Tkinter import *                # get base widget set from glob import glob                # filename expansion list import demoCheck                     # attach check button example to me import random                        # pick a picture at random gifdir = '../gifs/'                  # default dir to load GIF files class ButtonPicsDemo(Frame):     def _ _init_ _(self, gifdir=gifdir, parent=None):         Frame._ _init_ _(self, parent)         self.pack( )         self.lbl = Label(self,  text="none", bg='blue', fg='red')         self.pix = Button(self, text="Press me", command=self.draw, bg='white')         self.lbl.pack(fill=BOTH)         self.pix.pack(pady=10)         demoCheck.Demo(self, relief=SUNKEN, bd=2).pack(fill=BOTH)         files = glob(gifdir + "*.gif")         self.images = map(lambda x: (x, PhotoImage(file=x)), files)         print files     def draw(self):         name, photo = random.choice(self.images)         self.lbl.config(text=name)         self.pix.config(image=photo) if _ _name_ _ == '_ _main_ _': ButtonPicsDemo().mainloop( ) 

This version works the same way as the original, but it can now be attached to any other GUI where you would like to include such an unreasonably silly button.

Programming Python
Programming Python
ISBN: 0596009259
EAN: 2147483647
Year: 2004
Pages: 270
Authors: Mark Lutz

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: