I would like to show Images from the Internet in a Label. I can do it with Images from the harddisk. Then I looked for a way to do it with Photos from the Internet and I wrote the following code:
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
But I get the following error message:
*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*
What am I doing wrong? Thanks in advance
P.S.: I am using Linux, if that should matter.
Update:
In the meanwhile I updated my function. But it still doesn't show images. Does it maybe have to do with the api? Any ideas what I have to change?
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()
Thanks in advance