Skip to content
Advertisement

Unable to Load an Image from an URL at TKinter

My goal is to display an JPG image from an URL using tkinter python.

This is the stackoverflow link that I used as a reference. But when I try to run the code, I have received a bunch of error such as:

  • KeyError: b’R0l…….
  • AttributeError: ‘PhotoImage’ object has no attribute ‘_PhotoImage__photo’

Does anyone have the solution to this?

This is the code:

import tkinter as tk
from PIL import Image, ImageTk
from urllib.request import urlopen
import base64

root = tk.Tk()

URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"
u = urlopen(URL)
raw_data = u.read()
u.close()


b64_data = base64.encodestring(raw_data)
photo = ImageTk.PhotoImage(b64_data)

label = tk.Label(image=photo)
label.image = photo
label.pack()

root.mainloop()

Advertisement

Answer

The first error is not specifying the data parameter within ImageTk.PhotoImage(data=b64_data). However, I’m unsure why PhotoImage is unable to read base64 data.

A workaround would be to use BytesIO from the io module. You can pass in the raw data you read from the image into a BytesIO, open it in Image and then pass that into PhotoImage.

I found the code for opening the image from here.

import tkinter as tk
from PIL import Image, ImageTk
from urllib2 import urlopen
from io import BytesIO

root = tk.Tk()

URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"
u = urlopen(URL)
raw_data = u.read()
u.close()

im = Image.open(BytesIO(raw_data))
photo = ImageTk.PhotoImage(im)

label = tk.Label(image=photo)
label.image = photo
label.pack()

root.mainloop()

If anybody has a better answer as to why the encoding fails, it would be a more appropriate answer to this question.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement