我知道这个问题已经被问过几次了,但是我仍然无法弄清楚我的问题的答案。我不断收到相同的错误,不知道如何解决。
这是我的代码:
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()
它说图像存在于指定的路径,但是我不断收到此错误消息:
Traceback (most recent call last): File "ImageTest.py", line 31, in <module> label=Label(window, image=i) File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2597, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.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
我不知道如何解决这个问题。任何帮助,将不胜感激!
您应该使用PhotoImage实例作为image值。另外,您需要保留图像的参考。
PhotoImage
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