在python中,如何使用以下代码使图像出现在该按钮上?

2024-09-30 04:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 函数图像imageself程序hellotkinterdef
1条回答
网友
1楼 · 发布于 2024-09-30 04:26:49

您需要保留一个参考:

When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:

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

有关Tkinter照片的更多信息,请参见this page。在

相关问题 更多 >

    热门问题