Search code examples
pythonpython-3.ximagetkinterphotoimage

How do I make an image appear on this button in python with the following code?


So I need to get an image of mine on a button that I've created in python. But it pops up with the error (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image "pyimage2" doesn't exist. Also, I've made the main window of my program in a function. Then I've made it so when python has gone through that function it then opens up this startup window, where you can like login and access the LifeLoginWindow. But when I get rid of this startup and just call the LifeLoginWindow function, it runs perfectly and I can see the images. So I don't know what going on. Here is my code :

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()

Solution

  • You need to keep a reference:

    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()
    

    See this page for more on Tkinter PhotoImage.