我想從 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 模塊,是否有其他方法來制作隨機模因生成器。
uj5u.com熱心網友回復:
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()
uj5u.com熱心網友回復:
您需要使用Image.open(...)-Image是一個模塊,而不是一個類。您可以在官方 PIL 檔案中找到教程。
您可能需要先將回應內容放入一個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)
uj5u.com熱心網友回復:
我會用 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/536358.html
上一篇:如何繞過Laravel中的FormRequest驗證來存盤user_id?
下一篇:從獲取的資料中洗掉一個專案反應
