0

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()
Artemis
  • 2,553
  • 7
  • 21
  • 36
  • 2
    As [the docs](http://effbot.org/tkinterbook/photoimage.htm) mention, Tkinter can only load GIF and PGM/PPM images, it doesn't know how to load PNG, but you can read many other image formats using PIL (Pillow) and convert the resulting Image to a Tkinter PhotoImage via PIL's `ImageTk.PhotoImage`. Also, please read the Note at the end of that doc page. – PM 2Ring Oct 21 '17 at 12:50
  • I used the example from the docs mention. Which then I implemented abit. But it's still not working. And keep in mind some of my png images have loaded in. But the ones I keep in functions don't load in. But here's my code : StartUpIcon = PhotoImage(file = "Life Login Image Resized.png") label = Label(RegisterWindow,image=StartUpIcon) label.image = StartUpIcon # keep a reference! label.grid(row = 0, column = 2) – Ambrose Odongkara Oct 25 '17 at 10:49
  • You may find my scripts here helpful: https://stackoverflow.com/a/31498692/4014959 – PM 2Ring Oct 25 '17 at 10:57

1 Answers1

0

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.

Community
  • 1
  • 1
Artemis
  • 2,553
  • 7
  • 21
  • 36