使用PIL和Urllib检索URL时未找到图像

时间:2015-01-27 21:15:30

标签: python python-2.7 tkinter python-imaging-library urllib

无论我尝试使用哪种图片网址,我都会收到以下错误:

line 76, in <module>
    radar = Label(root, image = im)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2556, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2055, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
TclError: image "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=538x190 at 0x105D4A830>" doesn't exist

以下是一段代码:

    import pywapi, pprint, string, urllib, io
    from Tkinter import *
    from PIL import Image, ImageTk

    fd = urllib.urlopen("http://www.google.com/images/srpr/logo11w.png")
    imgFile = io.BytesIO(fd.read())
    im = Image.open(imgFile)
    image = Label(root, image = im)
    image.grid(row = 7, column = 1)

我认为使用标签需要PhotoImage,我不确定如何最好地进行。谢谢。

1 个答案:

答案 0 :(得分:2)

对我来说,以下代码有效。请检查您是否也这样做:

import urllib, io

from Tkinter import *
from PIL import Image, ImageTk


root = Tk()

fd = urllib.urlopen("http://www.google.com/images/srpr/logo11w.png")
imgFile = io.BytesIO(fd.read())
im = ImageTk.PhotoImage(Image.open(imgFile)) # <-- here
image = Label(root, image = im)
image.grid(row = 7, column = 1)

root.mainloop()

基本上,我添加了PhotoImage并将其传递给Label。还要检查你是否有zlib。枕头本身不读png。它继续external libraries

enter image description here