[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

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.


Viewing and Processing Images with PIL


As mentioned earlier, Python tkinter scripts show images by associating independently
created image objects with real widget objects. At this writing, tkinter GUIs can display
photo image files in GIF, PPM, and PGM formats by creating a PhotoImage object, as
well as X11-style bitmap files (usually suffixed with an .xbm extension) by creating a
BitmapImage object.


This set of supported file formats is limited by the underlying Tk library, not by tkinter
itself, and may expand in the future (it has not in many years). But if you want to display
files in other formats today (e.g., the popular JPEG format), you can either convert your
files to one of the supported formats with an image-processing program or install the
PIL Python extension package mentioned at the start of Chapter 7.


PIL, the Python Imaging Library, is an open source system that supports nearly 30
graphics file formats (including GIF, JPEG, TIFF, PNG, and BMP). In addition to al-
lowing your scripts to display a much wider variety of image types than standard tkinter,
PIL also provides tools for image processing, including geometric transforms, thumb-
nail creation, format conversions, and much more.


PIL Basics


To use its tools, you must first fetch and install the PIL package: see http://www.py
thonware.com (or search for “PIL” on the web). Then, simply use special PhotoImage
and BitmapImage objects imported from the PIL ImageTk module to open files in other
graphic formats. These are compatible replacements for the standard tkinter classes of
the same name, and they may be used anywhere tkinter expects a PhotoImage or
BitmapImage object (i.e., in label, button, canvas, text, and menu object configurations).


That is, replace standard tkinter code such as this:


from tkinter import *
imgobj = PhotoImage(file=imgdir + "spam.gif")
Button(image=imgobj).pack()

Viewing and Processing Images with PIL | 491
Free download pdf