How to Create a GUI Program in Python Using Tkinter
A Fun Fact Generator built with Tkinter: a button that calls a public facts API with requests and writes the result into a label. It is small enough to show the whole Tkinter cycle, from building the widgets to handling the click and updating the display.
Create the window
Tkinter ships with Python, so only requests needs installing (pip install requests). The script starts by importing both and creating the main window with a title and a size.
import json
import requests
from tkinter import *
window = Tk()
window.title("Fun Fact Generator")
window.geometry('800x80')
Fetch a fact from the API
The Useless Facts API returns one random fact as JSON on every GET request. These four lines fetch it and pull out the text; in the next step they become the body of the button function.
url = "https://uselessfacts.jsph.pl/api/v2/facts/random?language=en"
response = requests.request("GET", url)
data = json.loads(response.text)
useless_fact = data['text']
The video uses the older address random.json. The API now marks that version as deprecated and forwards it to the v2 address shown here, so I switched the code to v2.
Show the fact in the window
A button and a label do the rest. The button’s command points to get_fun_fact, which fetches a fact and writes it into the label with configure. Pass the function name without parentheses, or Tkinter calls it once at startup instead of on each click.
def get_fun_fact():
# Fetching the fun fact
url = "https://uselessfacts.jsph.pl/api/v2/facts/random?language=en"
response = requests.request("GET", url)
data = json.loads(response.text)
useless_fact = data['text']
lbl.configure(text=useless_fact)
btn = Button(window, text='Click Me', command=get_fun_fact)
btn.pack()
lbl = Label(window, text='Click the button to get a random fact')
lbl.pack()
The last line starts Tkinter’s event loop, which keeps the window open and reacts to clicks until you close it.
window.mainloop()
Full code
Here are all the pieces in one file. It fetches a new fact on every click.
import json
import requests
from tkinter import *
window = Tk()
window.title("Fun Fact Generator")
window.geometry('800x80')
def get_fun_fact():
url = "https://uselessfacts.jsph.pl/api/v2/facts/random?language=en"
response = requests.request("GET", url)
data = json.loads(response.text)
useless_fact = data['text']
lbl.configure(text=useless_fact)
btn = Button(window, text='Click Me', command=get_fun_fact)
btn.pack()
lbl = Label(window, text='Click the button to get a random fact')
lbl.pack()
window.mainloop()
The window freezes for the moment the request takes, because the call runs on Tkinter’s main thread. For a quick API that is fine. For a designed interface instead of the default widgets, I build the layout in Figma and convert it, as in my drag-and-drop GUI tutorial.
