2

Here is my code:

from tkinter import *

class app(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
        image = PhotoImage(file="image.gif")
        Label(image=image).pack()

window = app()
window.mainloop()

When I run the above code, the image is not displayed. However, when I run the following code...

from tkinter import *

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

root.mainloop()

...the image does show up. Why is this and how can I rectify it?

0

1 Answer 1

2

Replace:

image = PhotoImage(file="image.gif")
Label(image=image).pack()

with:

self.image = PhotoImage(file="image.gif")
Label(image=self.image).pack()

The image reference needs not to be garbage collected in order to be displayed.

Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I needed! Are there any other ways to solve the problem?
@MilanTom There can be a number of ways of solving. The key idea being keepinng the reference to the image object available in the scope which the image is shown. In the case above, it is the global scope.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.