pythonfunctiontkinterpython-imaging-library

tkinter images not opening in a function


I have a GUI class, and when you run it, it should open a toplevel tkinter window that has an image in it. This works when you simply run the class with test = GUI(), but when you run the class INSIDE a function, the images refuse to load.

DISCLAIMER: IF YOU RUN THE CODE BELOW YOU NEED TO HAVE YOUR OWN IMAGE & IMAGE PATH

import tkinter as tk
from PIL import Image,ImageTk

#GUI CLASS
class GUI:
    def __init__(self):
        self.toplevel = tk.Toplevel()
        
        self.img = ImageTk.PhotoImage(Image.open(IMAGE_PATH))
        self.img_label = tk.Label(self.toplevel,image=self.img)
        self.img_label.place(x=0,y=0)

#open the gui with a FUNCTION --> image doesn't open
def open_GUI():
    test = GUI()

#root window
root = tk.Tk()
tk.Label(root,text="This is the root").pack()

#tests
test = GUI()
open_GUI()

root.mainloop()

When you run the above code, it should open three windows. One is the root, and there is text to say. And two toplevels. What I expect is that two windows should have an image, and one with text (the root). However what actually happens is that there is one with text, one has an image (this is the hardcoded one), and one has no image (the one run the function).


Solution

  • To make sure that the GUI instance is not garbage collected, you can keep the reference in a global list:

    guis = []
    
    # Open the GUI with a FUNCTION --> image doesn't open
    def open_GUI():
        guis.append(GUI())