无法从 TKinter 的 URL 加载图像 [英] Unable to Load an Image from an URL at TKinter
问题描述
我的目标是使用 tkinter python 显示来自 URL 的 JPG 图像.
这是 stackoverflow 链接,我用作参考.但是当我尝试运行代码时,我收到了一堆错误,例如:
- 密钥错误:b'R0l......
- AttributeError: 'PhotoImage' 对象没有属性 '_PhotoImage__photo'
有没有人有解决办法?
这是代码:
导入 tkinter 作为 tk从 PIL 导入 Image、ImageTk从 urllib.request 导入 urlopen导入 base64根 = tk.Tk()URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"u = urlopen(URL)原始数据 = u.read()u.close()b64_data = base64.encodestring(raw_data)照片 = ImageTk.PhotoImage(b64_data)标签 = tk.Label(图像=照片)label.image = 照片标签.pack()root.mainloop()
第一个错误是没有在 ImageTk.PhotoImage(data=b64_data)
中指定 data
参数.但是,我不确定为什么 PhotoImage
无法读取 base64 数据.
一种解决方法是使用 io
模块中的 BytesIO
.您可以将从图像中读取的原始数据传入BytesIO
,在Image
中打开它,然后将其传入PhotoImage
.>
我从这里找到了打开图片的代码.
导入 tkinter 作为 tk从 PIL 导入 Image、ImageTk从 urllib2 导入 urlopen从 io 导入 BytesIO根 = tk.Tk()URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"u = urlopen(URL)原始数据 = u.read()u.close()im = Image.open(BytesIO(raw_data))照片 = ImageTk.PhotoImage(im)标签 = tk.Label(图像=照片)label.image = 照片标签.pack()root.mainloop()
如果有人对编码失败的原因有更好的答案,这将是对这个问题的更合适的答案.
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()
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.
这篇关于无法从 TKinter 的 URL 加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!