Skip to content

Instantly share code, notes, and snippets.

@wviana
Last active April 12, 2020 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wviana/5ce3095e00f003752033e9335a5af750 to your computer and use it in GitHub Desktop.
Save wviana/5ce3095e00f003752033e9335a5af750 to your computer and use it in GitHub Desktop.
Getting help about why does this code doesn't shows any image.
from PIL import Image, ImageTk
from io import BytesIO
import requests
import tkinter as tk
from collections import namedtuple
import sys
creative_common_image_url = 'https://api.creativecommons.engineering/v1/images'
default_params = {
'q': None,
'license': None,
'license_type': None,
'categories': 'illustration',
'extension': None,
'aspect_ratio': None,
'size': None,
'source': None,
'searchBy': None
}
ImageResult = namedtuple('ImageResult', 'preview url')
def request_image(url):
response = requests.get(url)
img_data = BytesIO(response.contet)
return Image.open(img_data)
def parse_results(result):
for r in result:
preview_url = r['thumbnail']
url = r['url']
if not any(map(lambda s: s.endswith('svg'), [preview_url, url])):
try:
preview = request_image(preview_url)
yield ImageResult(preview, url)
except:
...
def images(key_word):
params = default_params.copy()
params.update(q=key_word)
print(f'{key_word=}, {params=}')
response = requests.get(creative_common_image_url, params=params)
result = response.json()['results']
return list(parse_results(result))
root = tk.Tk()
for i in images('horse'):
# i is a pillow Image that had created with Image.open()
image = ImageTk.photoImage(i.preview)
label = tk.Label(root, image=image)
label.image = image
label.pack(side='left', fill='both', expand='yes')
break # braeking here so I test just test the first one.
root.mainloop()
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment