Python Tkinter PhotoImage

It does not matter much where you declare the image, as long as

  1. you create it after initializing Tk() (the problem in your first approach)
  2. the image is in the variable scope when you are using it (the problem in your second approach)
  3. the image object does not get garbage-collected (another common pitfall)

If you define the image in your main() method, then you will have to make it global

class MyCustomWindow(Tkinter.Frame):
    def __init__(self, parent):
        Tkinter.Frame.__init__(self, parent)
        Tkinter.Label(self, image=image).pack()
        self.pack(side="top")

def main():
    root = Tkinter.Tk()
    global image # make image known in global scope
    image = Tkinter.PhotoImage(file="image.gif")
    MyCustomWindow(root)
    root.mainloop()

if __name__ == "__main__":
    main()

Alternatively, you could drop your main() method entirely, making it global automatically:

class MyCustomWindow(Tkinter.Frame):
    # same as above

root = Tkinter.Tk()
image = Tkinter.PhotoImage(file="image.gif")
MyCustomWindow(root)
root.mainloop()

Or, declare the image in your __init__ method, but make sure to use the self keyword to bind it to your Frame object so it is not garbage collected when __init__ finishes:

class MyCustomWindow(Tkinter.Frame):
    def __init__(self, parent):
        Tkinter.Frame.__init__(self, parent)
        self.image = Tkinter.PhotoImage(file="image.gif")
        Tkinter.Label(self, image=self.image).pack()
        self.pack(side="top")

def main():
    # same as above, but without creating the image

Leave a Comment