From 6b7d49ec912cb4aac9e28e6e3e672074cee4eb7b Mon Sep 17 00:00:00 2001 From: EliStillCantCode Date: Sun, 5 Mar 2023 15:51:16 +0000 Subject: [PATCH 1/2] using an api lesson --- python/12-using-an-api.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 python/12-using-an-api.py diff --git a/python/12-using-an-api.py b/python/12-using-an-api.py new file mode 100644 index 0000000..f59195d --- /dev/null +++ b/python/12-using-an-api.py @@ -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 the window to stop it closing +myWindow.mainloop() \ No newline at end of file From cd75bf271a0d9394c4151a83d2a348b75fdfdec5 Mon Sep 17 00:00:00 2001 From: EliStillCantCode Date: Sun, 5 Mar 2023 16:00:32 +0000 Subject: [PATCH 2/2] correct mainloop explanation --- python/12-using-an-api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/12-using-an-api.py b/python/12-using-an-api.py index f59195d..a088475 100644 --- a/python/12-using-an-api.py +++ b/python/12-using-an-api.py @@ -27,5 +27,5 @@ myLabel = tkinter.Label(image=TkinterImage) myLabel.pack() # "pack" (add) the label to the window -# we now just add a mainloop() to the window to stop it closing +# we now just add a mainloop() to open the window myWindow.mainloop() \ No newline at end of file