Image GUI sourced from Internet Python



我正在尝试显示来自 URL 的图像,但我不确定该怎么做。以下是我的尝试:

imageFile = "http://photo.elsoar.com/wp-content/images/Personal-computer.jpg"
image1 =PhotoImage(open(imageFile))
image1.grid(row=1, column=5)

这只会产生错误

Traceback (most recent call last):
  File "C:UsersDerrenDesktopOnline Shopper.py", line 131, in <module>
image1 =PhotoImage(open(imageFile))

IOError: [Errno 22] 无效模式 ('r'( 或文件名: 'http://photo.elsoar.com/wp-content/images/Personal-computer.jpg'这是我想要的图像http://photo.elsoar.com/wp-content/images/Personal-computer.jpg

但是,必须从互联网而不是本地文件中获取资源

函数 open(( 仅适用于局部文件。您可以在此处查看文档第 7.2 部分。如果要使用联机映像,可以使用此映像:

from PIL import Image
import requests
from io import BytesIO
response = requests.get("url")
img = Image.open(BytesIO(response.content))
img.save("my_img.png") #with the good filename extension

如果您特别想要一个基于PhotoImage的解决方案,这应该可以工作:

import urllib
f = urllib.urlopen("http://photo.elsoar.com/wp-content/images/Personal-computer.jpg")
data=f.read()
root = Tkinter.Tk()
image1 =PhotoImage(data)

最新更新