首页 > 解决方案 > Tkinter PhotoImage in function doesn't appear

问题描述

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)

标签: pythontkinter

解决方案


我经常在这里看到这个问题:PhotoImage当函数完成/返回时,您的对象正在被垃圾收集。Tkinter 不知何故不喜欢这样(例如Button's 可以收集垃圾,Tkinter 以某种方式处理它,但PhotoImage's 不是这种情况)。您必须以某种方式保存这些图像,例如,首先在您的函数中创建框架,然后创建框架的图像属性,如下所示:

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

推荐阅读