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?

Anonymous Coder
  • 512
  • 1
  • 6
  • 22

1 Answers1

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.

Nae
  • 14,209
  • 7
  • 52
  • 79
  • This is exactly what I needed! Are there any other ways to solve the problem? – Anonymous Coder Mar 17 '18 at 19:30
  • @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. – Nae Mar 17 '18 at 19:33