【发布时间】:2021-07-03 11:54:51
【问题描述】:
我想在标签中显示来自 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*
我做错了什么?提前致谢
P.S.:我使用的是 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()
提前致谢
【问题讨论】:
标签: image tkinter base64 urllib