_tkinter.TclError:image" ..."不存在 [英] _tkinter.TclError: image "..." doesn't exist

查看:2396
本文介绍了_tkinter.TclError:image" ..."不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经被多次询问了,但我仍然无法找到问题的答案。我一直得到同样的错误,不知道如何解决。

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.

这是我的代码:

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:\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

我无法弄清楚如何解决这个问题。任何帮助将不胜感激!

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

推荐答案

您应该使用 PhotoImage 实例作为图片值。此外,您需要保留图像的参考。

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

这篇关于_tkinter.TclError:image&quot; ...&quot;不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆