python - 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)
解决方案
我经常在这里看到这个问题: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
推荐阅读
- java - 在 Maven 多模块项目的父配置中将模块设置为对其他模块的依赖项
- html - 不能在另一个 div 中水平居中 div
- kubernetes - 将 JHipster 项目部署到 Kubernetes 时出现“创建文件“/target”时出错”
- python - 为什么 return 语句不终止函数?
- c - 有人可以解释为什么 printf("%s", str + str[0] - str[3]); 在 C 中工作?
- ruby-on-rails - 如何从 rake 任务向前端发送数据(即如何与服务器发送的事件结合)?
- angular - 服务器端渲染实际上不是“渲染”的服务器端?
- node.js - 有没有办法处理发送到 NodeJS 中 HTTPS 端口的 HTTP 请求
- alibaba-cloud - 阿里巴巴 ACP 关于 CDN 的问题(需要说明)
- visual-studio-code - sam cli 调试 vscode