How to get a new API response in a Tkinter Textbox?

Published January 03, 2022

When we want to implement a particular feature or service in our GUI application, we use APIs. The APIs connect the client to an application server, which processes all the requests made by the client. Whenever the client sends a request using an API method, the server responds with a status code to the client, where 201 represents a successful response.

There are a number of API methods that you can use depending on the functionality of your application. You can use the DELETE, PUT, POST, and GET methods. However, other publicly available APIs are available for use, such as the Cat Facts API. To use these APIs, you only need to make use of the requests module, which is available in the Python library.

In this post, let's look at how you can get a new API response in a Tkinter textbox. We will display the response from the server in a Tkinter Textbox.

 

How to get a new API Response in a Tkinter Textbox

To make use of the API and retrieve data from the servers, you simply have to follow the following basic steps:

Step 1: First, import all the required libraries and request modules. Just run the "pip install requests" command.

Step 2: Now, in our application, create a text widget that will display all the API responses. In this tutorial, we will use the GET method.

Step 3: Create a variable to hold the API URL. Step 4:

Step 4: Define the function that will retrieve the JSON response and call the API

Step 5: Now, update the text widget with the response retrieved from the API based on the actions, such as deleting or entering new text.

Step 6: Make a button that will load the retrieved facts.

 

Example

In this example, we are going to fetch data and display it on our Tkinter Textbox

from tkinter import *

import requests

import json

win = Tk()

win.geometry("700x350")

win.title("Cat Fact API ")

text = Text(win, height=10, width=50, wrap="word")

text.config(font="Arial, 12")

label = Label(win, text="Cat Facts")

label.config(font="Calibri, 14")

api_url = "https://catfact.ninja/fact"

def get_zen():

   response = requests.get(api_url).text

   response_info = json.loads(response)

   Fact = response_info["fact"]

   text.delete('1.0', END)

   text.insert(END, Fact)

b1 = Button(win, text="Next", command=get_zen)

b2 = Button(win, text="Exit", command=win.destroy)

label.pack()

text.pack()

b1.pack()

b2.pack()

get_zen()

win.mainloop()

 

 

Python Tkinter API Response

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

378 Views