I want to read a image from api, but I am getting a error TypeError: 'module' object is not callable. I am trying to make a random meme generator
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"
I tried using python simple gui module, IS there alternative way to make a random meme generator.
CodePudding user response:
PIL.Image
is a module, you can not call it by Image(...), maybe you need call it by Image.open(...). At the same, tkinter/PySimpleGUI cannot handle JPG image, so conversion to PNG image is required.
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()
CodePudding user response:
You need to use Image.open(...)
- Image
is a module, not a class. You can find a tutorial in the official PIL documentation.
You may need to put the response content in a BytesIO
object before you can use Image.open
on it. BytesIO
is a file-like object that exists only in memory. Most functions like Image.open
that expect a file-like object will also accept BytesIO
and StringIO
(the text equivalent) objects.
Example:
from io import BytesIO
def get_image(url):
data = BytesIO(requests.get(url).content)
return Image.open(data)
CodePudding user response:
I would do it with tk its simple and fast
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()