tkinter and library PhotoImage tkinter and library PhotoImage tkinter tkinter

tkinter and library PhotoImage


The problem isn't about syntax -- it's about garbage collection. In your shortened form:

Label(root, image=PhotoImage(file="Image.gif")).pack()

the pointer to the image returned by PhotoImage() never gets saved, so the image gets garbage collected and doesn't display. In your longer form:

img = PhotoImage(file="Image.gif")Label(root, image=img).pack()

You're holding onto a pointer to the image, so everything works fine. You can convince yourself of this by wrapping the working code in a function and making img local to that function:

from tkinter import *root = Tk()def dummy():    img = PhotoImage(file="Image.gif")    Label(root, image=img).pack()dummy()mainloop()

Now, it won't display anymore because img disappears when the function returns and your image gets garbage collected. Now, return the image and save the returned value in a variable:

def dummy():    img = PhotoImage(file="Image.gif")    Label(root, image=img).pack()    return imgsaved_ref = dummy()

And your image works again! The common fix for this looks something like:

def dummy():    img = PhotoImage(file="Image.gif")    label = Label(root, image=img)    label.image_ref = img  # make a reference that persists as long as label    label.pack()dummy()

But you can see we've moved a long way away from a one-liner!


On the first version, img keeps the reference to the image.

On the second version, there is not reference to that image and pack() returns None