Home / Errors / tkinter-image-not-showing

Tkinter image not showing

The image was garbage collected. Keep a reference to the PhotoImage and it appears.

Tkinter image does not appear, or 'pyimage1' does not exist

The one line that fixes it

photo = ImageTk.PhotoImage(im)
label = tk.Label(root, image=photo)
label.image = photo
label.pack()

That label.image = photo line looks pointless and is not. Tk holds the image by name on its own side and keeps no Python reference, so as soon as the variable goes out of scope Python collects it and you get an empty box. Attaching it to the widget keeps it alive for as long as the widget lives.

Inside a function or a class

class App(ttk.Frame):
    def show(self, path):
        im = Image.open(path)
        im.thumbnail((400, 400))
        self.photo = ImageTk.PhotoImage(im)
        self.label.config(image=self.photo)

Store it on self. A local variable disappears the moment the method returns, which is why this bites inside functions far more often than at module level.

In a loop

self.photos = []
for path in paths:
    photo = ImageTk.PhotoImage(Image.open(path))
    self.photos.append(photo)
    tk.Label(self, image=photo).pack()

Keep the list for the lifetime of the window.

The pyimage1 variant

TclError: image "pyimage1" doesn't exist is usually the same problem, or a second Tk() instance. An application should create Tk() exactly once and use Toplevel() for extra windows.

And the format

Plain Tk reads GIF and PNG only. For JPEG and the rest, use Pillow's ImageTk as above. See the Tkinter introduction.

Still stuck

The PIL to Pillow converter finds most of these automatically, and the other error pages cover the rest.