【问题标题】:How do I make an image appear on this button in python with the following code?如何使用以下代码在 python 中的此按钮上显示图像?
【发布时间】:2017-10-21 12:12:23
【问题描述】:

所以我需要在我用 python 创建的按钮上获取我的图像。但它弹出错误(widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image "pyimage2" doesn't exist。另外,我已经在一个函数中制作了我的程序的主窗口。然后我做到了,所以当python完成该功能时,它会打开这个启动窗口,您可以在其中登录并访问LifeLoginWindow。但是当我摆脱这个启动并只调用LifeLoginWindow 函数时,它运行完美,我可以看到图像。所以我不知道发生了什么。这是我的代码:

from tkinter import*

def hello():
    print("Works, and hello!")

def LifeLoginWindow():
    window = Tk()

    TrendsButton = PhotoImage(file = "Trends_Button.png")
    TrendsButton_label = Button(SideBar, image = TrendsButton, command = hello)
    TrendsButton_label.pack(side=TOP)
    SideBar.pack(side = LEFT, fill = Y)
    window.mainloop()

StartUp = Tk()
def LoginFunction():
    StartUp.destroy
    LifeLoginWindow()

StartUpIcon = PhotoImage(file = "Life Login Image Resized.png")
StartUpIcon_label = Label(StartUp, image = StartUpIcon)
StartUpIcon_label.grid(row = 0, column = 2)
LoginButt = Button(StartUp, text = "Login", command = LoginFunction)
LoginButt.grid(row = 3, column = 2)

print("_Loaded Start Up...")

StartUp.mainloop()

【问题讨论】:

  • 正如the docs 提到的,Tkinter 只能加载 GIF 和 PGM/PPM 图像,它不知道如何加载 PNG,但是您可以使用 PIL (Pillow) 读取许多其他图像格式并转换通过 PIL 的ImageTk.PhotoImage 将生成的图像转换为 Tkinter PhotoImage。另外,请阅读该文档页面末尾的注释。
  • 我使用了文档中提到的示例。然后我实施了。但它仍然无法正常工作。请记住,我的一些 png 图像已加载。但我保留在函数中的那些没有加载。但这是我的代码: StartUpIcon = PhotoImage(file = "Life Login Image Resized.png") label = Label( RegisterWindow,image=StartUpIcon) label.image = StartUpIcon # 保留参考! label.grid(row = 0, column = 2)
  • 您可能会发现我的脚本在这里很有帮助:stackoverflow.com/a/31498692/4014959

标签: python python-3.x image tkinter photoimage


【解决方案1】:

你需要保留一个参考:

当 Python 对 PhotoImage 对象进行垃圾收集时(例如,当您从将图像存储在局部变量中的函数返回时),即使图像正在由 Tkinter 小部件显示,也会被清除。

为避免这种情况,程序必须保留对图像对象的额外引用。一种简单的方法是将图像分配给小部件属性,如下所示:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

有关 Tkinter PhotoImage 的更多信息,请参阅this page

【讨论】:

    猜你喜欢
    • 2020-10-13
    • 2018-01-06
    • 2020-11-18
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多