Reputation: 1185
I have a button that shows a new frame with a picture label in it. The label and image are exactly as they are in all the tutorials but the picture doesn't show. It is a .gif. What am I doing wrong? Here is my code:
from Tkinter import *
class Main(object):
def __init__(self, root):
self.f1=Frame(root)
self.f1.grid()
b1=Button(f1, command=self.photo, text="Picture")
b1.grid()
def photo(self):
self.f1.destroy()
self.f2=Frame(root)
self.f2.grid()
self.img1=PhotoImage("CO2_Levels.gif")
self.l3=Label(self.f2, image=self.img1)
self.l3.image=self.img1
self.l3.grid()
root=Tk()
app=Main(root)
root.mainloop()
Upvotes: 1
Views: 1397
Reputation: 192
I know this is an old question. But if anyone run into the same problem, this is because the image gets garbage collected when you return from the function. To avoid this you should keep a reference to the image object. your photo method,
def photo(self):
self.f1.destroy()
self.f2=Frame(root)
self.f2.grid()
self.img1=PhotoImage("CO2_Levels.gif")
self.l3=Label(self.f2, image=self.img1)
self.l3.image = self.img1 # Reference to the image object
self.l3.image=self.img1
self.l3.grid()
Source : http://effbot.org/tkinterbook/photoimage.htm
Upvotes: 2
Reputation: 386342
The default first argument is name for the image. If you are giving it a file path you need to specify file=
in front of the path so that PhotoImage knows it's the path to the file rather than the name of the image.
self.img1=PhotoImage(file="CO2_Levels.gif")
Upvotes: 0