0

所以我需要在我用 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()
4

1 回答 1

0

您需要保留参考:

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

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

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

有关 Tkinter PhotoImage 的更多信息,请参阅此页面

于 2018-04-11T14:43:13.447 回答