【问题标题】:my button in tkinter is not showing the image [duplicate]我在 tkinter 中的按钮没有显示图像 [重复]
【发布时间】:2021-04-30 03:20:16
【问题描述】:

此代码只是一个示例 代码:

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 tkinter


【解决方案1】:

当图像在函数中时,您必须保持对图像的引用,否则它将被 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。此问题应标记为重复并已关闭,但以防万一您不了解在“特定情况”中该怎么做,这是答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多