Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - _tkinter.TclError: image "..." doesn't exist

I know that this question has already been asked several times, but I still couldn't figure out the answer to my problem. I keep getting the same error and don't know how to solve it.

This is my code:

from Tkinter import *
from PIL import Image, ImageTk
import os

window = Tk()
i = Image.open(pathToImage) 
if os.path.isfile(pathToImage):

     print 'image exists'
else:   
     print 'image does not exits'

label=Label(window, image=i)
label.pack()
window.mainloop()

It says that the image exists at the indicated path, but I keep getting this error message:

Traceback (most recent call last):
  File "ImageTest.py", line 31, in <module>
    label=Label(window, image=i)
  File "C:UsersusernameAnaconda2liblib-tkTkinter.py", line 2597, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
  File "C:UsersusernameAnaconda2liblib-tkTkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=640x480 at 0x36DF278>" doesn't exist

I could not figure out how to solve this problem. Any help would be appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use PhotoImage instance as image value. Also, you need to keep the reference of your image.

im = Image.open(pathToImage)
ph = ImageTk.PhotoImage(im)

label = Label(window, image=ph)
label.image=ph  #need to keep the reference of your image to avoid garbage collection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...