# Brian Eastwood # 2/18/2012 # Utility for working with Python Image Library (PIL). # import PIL and the tk graphics packages import Tkinter import Image, ImageTk class ImageWindow(object): ''' A class that displays images in a Tkinter window. Note that this class is a singleton, so it should only be instantiated once. Access to the instance is through the static instance() method. ''' __instance = None @staticmethod def instance(): if ImageWindow.__instance is None: ImageWindow.__instance = ImageWindow() return ImageWindow.__instance def __init__(self): ''' Construct an ImageWindow. This sets up the Tkinter root window, a label, and an image object. ''' self.root = Tkinter.Tk() self.root.title("Image Window") self.tklabel = Tkinter.Label(self.root, image=None) self.tkimage = None # set up tk event bindings self.root.bind("", self.onKey) def onKey(self, event): ''' Handles destroying the root window if q or esc is pressed. Parameters: event - the tk key event ''' if event.char == 'q' or event.char == '\x1b': self.root.destroy() def setImage(self, image, title=None): ''' Sets the image displayed in the window. Parameters: image - the PIL Image to display title - a title for the image window (optional) ''' # ensure image is proper type if not isinstance(image, Image.Image): print "ERROR: This is not a recognized PIL image: {0}".format(type(image)) print "Use img = Image.open(\"filename.jpg\") to open an image file." return # update the image self.tkimage = ImageTk.PhotoImage(image) self.tklabel.config(image=self.tkimage) # update the title if title is not None: self.root.title(title) # ensure the image displays self.tklabel.pack() self.root.update() def display(image, title=None): ''' Displays a PIL Image in a window. Parameters: image - the PIL Image to display; must be an Image object title - the title for the image window (optional) ''' ImageWindow.instance().setImage(image, title) def wait(): ''' Pauses the application until the image window is closed or q or esc is pressed. ''' Tkinter.mainloop() def test(): ''' Test the functions defined in this file. ''' import time filename = "icon.jpg" img = Image.open(filename) tkimg = display(img, "foo") tkimg = display(img, "blah") wait() if __name__ == "__main__": test()