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 = """

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 ="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!

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!

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