首页 > 解决方案 > Python3 tkinter:在标签(urllib)上显示来自互联网的图像不起作用

问题描述

我想在标签中显示来自 Internet 的图像。我可以用硬盘中的图像来做到这一点。然后我从互联网上寻找一种使用照片的方法,并编写了以下代码:

    self.res = requests.get('https://dog.ceo/api/breeds/image/random')
    print(self.res)
    self.jason = json.loads(self.res.content)
    print (self.jason)
    bild = self.jason['message']
    print (bild)
    u = urllib.request.urlopen(bild)
    raw_data = u.read()
    u.close()
    b64_data = base64.encodestring(raw_data)
    image = tk.PhotoImage(data = b64_data)
    self.pic_label["image"] = image

但我收到以下错误消息:

*Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/home/wolfgang/Eigene Programme/python_buch/api.py", line 42, in api
image = tk.PhotoImage(data = b64_data)
File "/usr/lib/python3.6/tkinter/__init__.py", line 3545, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python3.6/tkinter/__init__.py", line 3501, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize image data*

我究竟做错了什么?提前致谢

PS:我正在使用Linux,如果这很重要的话。

更新:

与此同时,我更新了我的功能。但它仍然不显示图像。它可能与api有关吗?有什么想法我必须改变吗?

def api(self):
    

    self.res = requests.get('https://dog.ceo/api/breeds/image/random')
    print(self.res)
    self.jason = json.loads(self.res.content)
    print (self.jason)
    bild = self.jason['message']
    image_bytes = urllib.request.urlopen(bild).read()
    data_stream = io.BytesIO(image_bytes)
    pil_image = Image.open(data_stream)
    tk_image = ImageTk.PhotoImage(pil_image)
    
    self.anzeige = tk.Label(self.root,image=tk_image)
    self.anzeige.pack()

提前致谢

标签: imagetkinterbase64urllib

解决方案


当我运行您的代码时,它返回了一个 jpg 图像。该类tkinter.PhotoImage不直接支持 jpg。您需要使用 PIL/Pillow 创建图像并将其交给 tkinter,或者在创建PhotoImage.

有关如何在 tkinter 中显示 jpeg 图像,请参阅如何将 JPEG 图像插入 python Tkinter 窗口?


推荐阅读