如何从api url在python简单gui中显示图像



我想从api读取图像,但我得到一个错误TypeError: 'module'对象不可调用。我正在尝试制作一个随机模因生成器

import PySimpleGUI as sg
from PIL import Image
import requests, json 

cutURL = 'https://meme-api-python.herokuapp.com/gimme'
imageURL = json.loads(requests.get(cutURL).content)["url"]
img = Image(requests.get(imageURL).content)


img_box = sg.Image(img)

window = sg.Window('', [[img_box]])
while True:
event, values = window.read()
if event is None:
break
window.close()
Here is the response of the api 
postLink    "https://redd.it/yyjl2e"
subreddit   "dankmemes"
title   "Everything's fixed"
url "https://i.redd.it/put9bi0vjp0a1.jpg" 

我尝试使用python简单的gui模块,是否有替代方法来制作随机模因生成器。

PIL.Image是一个模块,您不能通过Image(…)调用它,也许您需要通过Image.open(…)调用它。同时,tkinter/PySimpleGUI无法处理JPG图像,因此需要转换为PNG图像。

from io import BytesIO
import PySimpleGUI as sg
from PIL import Image
import requests, json
def image_to_data(im):
"""
Image object to bytes object.
: Parameters
im - Image object
: Return
bytes object.
"""
with BytesIO() as output:
im.save(output, format="PNG")
data = output.getvalue()
return data
cutURL = 'https://meme-api-python.herokuapp.com/gimme'
imageURL = json.loads(requests.get(cutURL).content)["url"]
data = requests.get(imageURL).content
stream = BytesIO(data)
img = Image.open(stream)
img_box = sg.Image(image_to_data(img))
window = sg.Window('', [[img_box]], finalize=True)
# Check if the size of the window is greater than the screen
w1, h1 = window.size
w2, h2 = sg.Window.get_screen_size()
if w1>w2 or h1>h2:
window.move(0, 0)
while True:
event, values = window.read()
if event is None:
break
window.close()

您需要使用Image.open(...)-Image是一个模块,而不是一个类。您可以在PIL官方文档中找到教程。

您可能需要将响应内容放在BytesIO对象中,然后才能对其使用Image.openBytesIO是一个只存在于内存中的类文件对象。大多数函数,如Image.open,需要一个类文件对象,也将接受BytesIOStringIO(文本等效)对象。

的例子:

from io import BytesIO
def get_image(url):
data = BytesIO(requests.get(url).content)
return Image.open(data)

我会用tk来做,它既简单又快速

def window():
root = tk.Tk()
panel = Label(root)
panel.pack()
img = None
def updata():
response = requests.get(https://meme-api-python.herokuapp.com/gimme)
img = Image.open(BytesIO(response.content))
img = img.resize((640, 480), Image.ANTIALIAS) #custom resolution
img = ImageTk.PhotoImage(img)
panel.config(image=img)
panel.image = img

root.update_idletasks()
root.after(30, updata)
updata()
root.mainloop()

最新更新