问题描述
限时送ChatGPT账号..这段代码只是一个例子代码:
this code is just an example code:
import tkinter as tk
root = tk.Tk()
photoImageObj = tk.PhotoImage(file="signout.png")
lab = tk.Label(root, image=photoImageObj).pack()
photoImageObjj = tk.PhotoImage(file="signout.png")
signout_button=tk.Button(root,image=photoImageObjj).pack()
root.mainloop()
在这段代码中,它工作正常,输出也工作正常.这是输出:但在我的实际项目中,我使用带有图像的按钮不起作用.代码:
In this code it is working and output is also working fine. here is the output: but in my real project, where I am using this button with the image is not working. code:
photoImageObj = PhotoImage(file="signout.png")
signout_button=Button(stem,image=photoImageObj).pack()
这里我没有粘贴我的全部代码,因为它有 50-60 行代码.输出:
here I haven't pasted my whole code since it is having 50-60 line's of code. Output:
所以如果相同的代码工作正常,那么我的真实项目文件就有问题.谁能帮我调试一下.
so if the same code is working fine, then there is problem in my real project file. so can anyone help me debug that.
推荐答案
当一个图像在一个函数中时,你必须保持对图像的引用,否则它会被 python 垃圾收集.提供的代码很难说,但请尝试以下操作:
When an image is inside a function you have to keep reference to the image or it will be garbage collected by python. With the code provided its hard to say, but just try something like:
signout_button = Button(stem,image=photoImageObj)
signout_button.pack() #so that signout_button is not None
signout_button.image=photoImageObj #keeping a reference
或者,您也可以在函数之上说global photoImageObj
,但不建议使用global
.此问题应标记为重复并关闭,但以防万一您不明白在特定情况"中该做什么,这里是答案.
Alternatively, you could also say global photoImageObj
on top of function, but its not recommended to use global
. This question should be marked as a duplicate and closed, but just in-case you dont understand what to do in your "specific case", here is the answer.
这篇关于我在 tkinter 中的按钮没有显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论