tkinter doesn't display image from outside the main file in a label

41 views Asked by At

Ok, the code works fine when I execute it directly. If I put it in a class or function, the widget has the correct size and gets displayed, but stays gray. Why is that? Any name space issue that I don't get?

#doesn't work

def example(tk, mainWindow):
    moretracer = tk.PhotoImage(file="tracer-closeup.png")
    trcl=tk.Label(mainWindow.L1_tabs["editreward"]["box"], image=moretracer,  bd=0)  
    trcl.pack()
example(tk,mainWindow)

#works

moretracer = tk.PhotoImage(file="tracer-closeup.png")
trcl=tk.Label(mainWindow.L1_tabs["editreward"]["box"], image=moretracer, bd=0)
trcl.pack()

edit: Ok, I read the other answer, and while using self.something doesn't apply here, the reference part is true, the garbage collector ate it. So this is the working solution:

def addimage(tk, mainWindow):
    moretracer = tk.PhotoImage(file="tracer-closeup.png")
    trcl=tk.Label(mainWindow.L1_tabs["editreward"]["box"],  image=moretracer, bd=0)  
    trcl.pack()
    return moretracer
e = addimage(tk,mainWindow)
0

There are 0 answers