Skip to content

lesson 12: using an api #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions python/12-using-an-api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# we're going to use a module called requests to handle our API
import requests

# we're going to use the API from randomfox.ca which gives us an image
dictionary = requests.get("https://randomfox.ca/floof/").json() # gives us a dictionary with two parts, the one we want is called: image, and is the url to the fox's image (example - ./image.png)
imageurl = dictionary["image"]

# now we can use Tkinter to display this image
import tkinter
myWindow = tkinter.Tk()

# we want to get the data from our imageurl
alldata = requests.get(imageurl)

# .content gives our data in a byte array
bytearray = alldata.content

# we're going to use BytesIO to convert our array into a photo
from io import BytesIO
from PIL import Image
photo = Image.open(BytesIO(bytearray))

# we're going to use ImageTK to add an image to a Tkinter label
from PIL import ImageTk
TkinterImage = ImageTk.PhotoImage(photo)

myLabel = tkinter.Label(image=TkinterImage)
myLabel.pack() # "pack" (add) the label to the window

# we now just add a mainloop() to open the window
myWindow.mainloop()