Reputation: 31
Why is my Tkinter image not working? It is in the same directory, all commands are right but I get the error:
_tkinter.TclError: image "pyimage1" doesn't exist.
What's wrong?
fertig=tkinter.Tk()
fertig.title("Window")
text=tkinter.Label(fertig,text="Success")
text.pack()
w = tkinter.PhotoImage(file="/Users/Hannes/Desktop/Spambot/successful.gif ")
w = tkinter.label(fertig,image=w)
w.pack()
knapp=tkinter.Button(fertig,text="Ok",command=lambda:close())
knapp.pack()
knapp.mainloop()
Upvotes: 1
Views: 5985
Reputation: 123541
The following works for me on my Windows system. I had to fix and add a few (unrelated) things to get the code in your question to work, but after doing so I found the real reason the image doesn't display.
So, the error that relates most directly to the that problem is because you're overwriting the variable w
: After you assign a tkinter.PhotoImage()
value to it, you immediately assign a another value (the tkinter.Label
) to using its current value (image=w
). The second assignment causes the tkinter.PhotoImage()
object that was in it to be lost. Since there are no more references to to, it will be garbage-collected at some point.
To fix that, I simply assign the PhotoImage
object to a separate variable img
.
Note, too, that (apparently) having the trailing space character in the filename isn't a problem (at least not on Windows).
Here's some "official" documentation specifically about the PhotoImage
class that discusses the need for keeping a reference around to the original—see the NOTE: at the end—when using it with other tkinter widgets (like a Label
).
import tkinter
def close(): # just a placeholder implementation.
print('close() called')
fertig=tkinter.Tk()
fertig.title("Window")
text=tkinter.Label(fertig, text="Success")
text.pack()
#w = tkinter.PhotoImage(file="/Users/Hannes/Desktop/Spambot/successful.gif ")
img = tkinter.PhotoImage(file=r"C:\vols\Files\PythonLib\Stack Overflow\successful.gif ")
w = tkinter.Label(fertig, image=img)
w.pack()
knapp=tkinter.Button(fertig, text="Ok", command=lambda: close())
knapp.pack()
knapp.mainloop()
Here's what it looks like (using an image of my own).
Upvotes: 2