【发布时间】: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