这段代码只是一个示例代码:
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()
在此代码中,它可以正常工作,并且输出也可以正常工作。这里是输出:但是在我的真实项目中,我在此按钮上使用图像的按钮不起作用。码:
photoImageObj = PhotoImage(file="signout.png")
signout_button=Button(stem,image=photoImageObj).pack()
这里没有粘贴我的整个代码,因为它包含50-60行代码。输出:
因此,如果相同的代码运行正常,则我的真实项目文件中存在问题。谁能帮我调试一下。
当图像在函数内部时,您必须保留对该图像的引用,否则它将被python垃圾收集。使用提供的代码很难说,但是只需尝试以下操作:
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
。该问题应标记为重复并关闭,但是如果万一您不了解在“特定情况”下该怎么做,这就是答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句