0

I am using following code to display an image on my Tkinter GUI, but only a blank frame is getting displayed.

import Tkinter as tk class my_gui(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        img = tk.PhotoImage(file=PATH_TO_GIF)
        panel = tk.Label(self, image = img)
        panel.grid()

app = my_gui()

app.mainloop()

However, the following code works:

import Tkinter as tk
root=tk.Tk()

img = tk.PhotoImage(file=PATH_TO_GIF)
panel = tk.Label(root, image = img)
panel.grid()

root.mainloop()

Any idea what the problem with the first script is?

jc1099
  • 35
  • 1
  • 7

2 Answers2

1

The widgets you create are thrown away as soon as the __init__() function ends. To fix this, save them as instance variables with self:

import Tkinter as tk 
class my_gui(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.img = tk.PhotoImage(file=PATH_TO_GIF)
        self.panel = tk.Label(self, image = self.img)
        self.panel.grid()

app = my_gui()

app.mainloop()
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Personally, I like saving the image as an attribute of the Label like `self.panel.image = img` better, since you don't fill up your namespace with variables that you don't need to reference anymore, there is a smaller chance of accidentally overwriting it with another image and you can be sure that the image stays around exactly as long as the Label. – fhdrsdg May 13 '15 at 09:41
0

@SimranjotSingh, what are trying to do is display the image in a class. The mainloop function is specifically meant for the parent window or frame. If you need to call the instance of your class you should call it like:

Instance_name = class_name(desired parameters)

However in your program you need to the image to a label and not directly to the root/window.

You can alse check out these:

Attempting to add a simple image into a label

How to add an image in Tkinter (Python 2.7)

Community
  • 1
  • 1
AkaiShuichi
  • 144
  • 1
  • 1
  • 9