【问题标题】:How to display images in python simple gui from a api url如何从 api url 在 python 简单 gui 中显示图像
【发布时间】:2022-11-20 01:41:56
【问题描述】:
我想从 api 读取图像,但收到错误 TypeError: 'module' object is not callable。我正在尝试制作一个随机模因生成器
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 模块,是否有其他方法来制作随机模因生成器。
【问题讨论】:
标签:
python
api
pysimplegui
【解决方案1】:
您需要使用 Image.open(...) - Image 是一个模块,而不是一个类。您可以在the official PIL documentation 找到教程。
您可能需要将响应内容放入 BytesIO 对象中,然后才能在其上使用 Image.open。 BytesIO 是一个只存在于内存中的类文件对象。大多数像 Image.open 这样期望类文件对象的函数也将接受 BytesIO 和 StringIO (等效文本)对象。
例子:
from io import BytesIO
def get_image(url):
data = BytesIO(requests.get(url).content)
return Image.open(data)
【解决方案2】:
我会用 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()
【解决方案3】:
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()