Search code examples
pythontkinterphotoimage

Tkinter PhotoImage in a class won't show


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()

Solution

  • 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")