How To Create A GUI Program In Python Using Tkinter
Introduction
In this blog post, I will walk you through how to create a Fun Fact Generator using Python’s Tkinter library. This simple GUI application will fetch random fun facts from an API and display them when a button is clicked.
Getting Started with Tkinter
To begin, I need to import the necessary libraries, specifically requests for making HTTP requests and tkinter for the GUI components. The first step is to set up the main window for the application:
import json import requests from tkinter import * window = Tk() window.title("Fun Fact Generator") window.geometry('800x80')
Here, I create a window titled “Fun Fact Generator” with specified dimensions.
Fetching Fun Facts
Next, I define a function to fetch a fun fact from the API. The endpoint I will be using is:
url = "https://uselessfacts.jsph.pl/random.json?language=en" response = requests.request("GET", url) data = json.loads(response.text) useless_fact = data['text']
This function makes a GET request to the specified URL, retrieves the JSON response, and extracts the fun fact text.
Displaying the Fun Fact
Now, I need to display the fetched fun fact in the GUI. To do this, I will create a label and a button. When the button is clicked, it will call the function to get a fun fact and update the label:
def get_fun_fact(): # Fetching the fun fact url = "https://uselessfacts.jsph.pl/random.json?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()
In this code, the button is labeled “Click Me” and is set to trigger the get_fun_fact function when clicked. The label is initialized with a prompt for the user.
Finalizing the GUI
Finally, I need to start the main loop of the Tkinter application to make everything functional:
window.mainloop()
This command keeps the window open and responsive to user interactions.
Conclusion
In this tutorial, I’ve shown how to create a simple Fun Fact Generator using Python and Tkinter. This application fetches random fun facts from an API and displays them in a user-friendly interface. It’s a great project to get started with GUI programming in Python!