back next

The Tkinter PhotoImage Class

The PhotoImage class is used to display images (either grayscale or true color images) in labels, buttons, canvases, and text widgets.

When to use the PhotoImage Class

You can use the PhotoImage class whenever you need to display an icon or an image in a Tkinter application.

Patterns #

The PhotoImage class can read GIF and PGM/PPM images from files:

photo = PhotoImage(file="image.gif")

photo = PhotoImage(file="lenna.pgm")

The PhotoImage can also read base64-encoded GIF files from strings. You can use this to embed images in Python source code (use functions in the base64 module to convert binary data to base64-encoded strings):

 
photo = """
R0lGODdhEAAQAIcAAAAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4O
Dg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEh
...
AfjHtq1bAP/i/gPwry4AAP/yAtj77x+Af4ABAwDwrzAAAP8SA/j3DwCAfwAA/JsM4J/lfwD+/QMA
4B8AAP9Ci/4HoLTpfwD+qV4NoHVAADs=
"""

photo = PhotoImage(data=photo)

If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects:

from PIL import Image, ImageTk

image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)

You can use a PhotoImage instance everywhere Tkinter accepts an image object. An example:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.

Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
 

A Django site. rendered by a django application. hosted by webfaction.