-1

I'm creating a little program to show if something is ok, but I have a problem with the images. It was working until I create a function to generate my page Without images

def genTout(matInput):
    #images
    vert_off = PhotoImage(file=r".\asset\vert_off.png")
    rouge_off = PhotoImage(file=r".\asset\rouge_off.png")
    vert_on = PhotoImage(file=r".\asset\vert_on.png")
    rouge_on = PhotoImage(file=r".\asset\rouge_on.png")

    #frame
    rightFrame = Frame(highlightbackground="black",highlightthickness=5 ,bg="grey")
    buttonControl = Frame(rightFrame,highlightbackground="black",highlightthickness=5 ,bg="grey")

    
    for i in range(0,4):
        Label(buttonControl,text=i+1).grid(row=0,column=i+2)
        Label(buttonControl,image=(vert_on if matInput[i*2] == 0 else vert_off)).grid(row=1,column=i+2)
        Label(buttonControl,image=(rouge_on if matInput[i*2+1] == 0 else rouge_off)).grid(row=2,column=i+2)

    return frame

When i take my code on the main it's working but if I put the code inside a function no images appear

Here is my main where I get the return

root = Tk()
PanelView = PanedWindow(width=100, bd=5,relief="raised",bg="grey")
PanelView.pack(fill=BOTH,expand=1)
#my side bar code
...

rightFrame = genTout(matInput)
PanelView.add(rightFrame)
TheEagle
  • 5,808
  • 3
  • 11
  • 39
scipy
  • 1
  • 2

1 Answers1

0

I saw that problem often already here : Your PhotoImage objects are getting garbage collected when the function finishes / returns. Tkinter somehow doesn't like that (for example Button's can get garbage collected, Tkinter somehow deals with it, but that's not the case for PhotoImage's). You must somehow save these images, for example by creating the frame first thing in your function and then making the images attributes of the frame, like this:

def genTout(matInput):
    #frame
    rightFrame = Frame(highlightbackground="black", highlightthickness=5 , bg="grey")
    buttonControl = Frame(rightFrame, highlightbackground="black", highlightthickness=5, bg="grey")

    #images
    rightFrame.vert_off = PhotoImage(file=r".\asset\vert_off.png")
    rightFrame.rouge_off = PhotoImage(file=r".\asset\rouge_off.png")
    rightFrame.vert_on = PhotoImage(file=r".\asset\vert_on.png")
    rightFrame.rouge_on = PhotoImage(file=r".\asset\rouge_on.png")

    
    for i in range(0, 4):
        Label(buttonControl, text=i + 1).grid(row=0, column=i + 2)
        Label(buttonControl, image=(rightFrame.vert_on if matInput[i * 2] == 0 else rightFrame.vert_off)).grid(row=1, column=i+2)
        Label(buttonControl, image=(rightFrame.rouge_on if matInput[i * 2 + 1] == 0 else rightFrame.rouge_off)).grid(row=2, column=i + 2)

    return frame
TheEagle
  • 5,808
  • 3
  • 11
  • 39