Open In App

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

Last Updated : 25 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will look into how to make an API request and then insert it into a Tkinter textbox using Python, Before moving further we will cover some basic concepts related to our article that we will use frequently.

  • Request: Requests are required to play with the web. If you want to use APIs, download entire Facebook pages, or do anything else nice, you’ll need to make a request to the URL. When it comes to REST APIs and Web scraping, requests are crucial.
  • Tkinter: Tkinter is the most commonly used method. It’s a standard Python interface to the Python-supplied Tk GUI toolkit. The fastest and simplest approach to constructing GUI applications is with Python and Tkinter. Using Tkinter to create a GUI is a simple operation.
  • API: APIs usually allow us to get information from a server which helps us in our projects. We make requests to APIs using different methods like example GET, POST, etc

Packages Required

To make a GUI we need to install Tkinter.

pip install tkinter

To make an API request, we usually use a python library called requests

pip install requests

Stepwise Implementation

Step 1:  Making an API request

To make a GET request to an API, we use the requests.get() method. For this tutorial, we will be using an Open-Source API called Quotable. It has a route ‘/random’ which gives us a random quote.

Python3




import requests
  
# Response Object
r = requests.get('https://api.quotable.io/random')


Step 2: Getting the data from the API Request

Usually, APIs return the data in a JSON format. But, our requests library makes it easier for us and converts it into a python dictionary object. We can get that data by the r.json() method:

Python3




import requests
  
r = requests.get('https://api.quotable.io/random')
data = r.json()


Output:

{‘_id’: ‘w4QwG7e8hNr7’, ‘tags’: [‘famous-quotes’], ‘content’: ‘The only Zen you find on the tops 
of mountains is the Zen you bring up there.’, ‘author’: ‘Robert M. Pirsig’, ‘authorSlug’: ‘robert-m-pirsig’, ‘length’: 77, ‘dateAdded’: ‘2019-02-17’, ‘dateModified’: ‘2019-02-17’}

Step 4: In this dictionary, we only import data that are present in the ‘content’ key which we can further store in a variable

quote = data['content']

Step 5: Creating a basic Tkinter App

So, here we have a very basic Tkinter app with a Textbox and a button

Python3




import tkinter as tk
from tkinter import END, Text
from tkinter.ttk import Button
  
root = tk.Tk()
root.title('Quoter')
text_box = Text(root, height=10, width=50)
get_button = Button(root, text="Get Quote", command=get_quote)
  
text_box.pack()
get_button.pack()
root.mainloop()


Step 6: Creating an API Request function

We will now make a function that will get the data from the API, and edit the Text Box with that data:

  • The text_box.delete() deletes all the text that is currently in the TextBox widget from the specified Index. In this case, It’s from 1.0 to the end which means the whole TextBox will be cleared.
  • The text_box.insert() inserts data into the TextBox from the specified index. As the index is END, which in our case will be the first index, It will insert the quote obtained from the API to the TextBox.

Python3




def get_quote():
    r = requests.get('https://api.quotable.io/random')
    data = r.json()
    quote = data['content']
    text_box.delete('1.0', END)
    text_box.insert(END, quote)   


Code Implementation

Python3




# import library
import requests
import tkinter as tk
from tkinter import END, Text
from tkinter.ttk import Button
  
# create a main window
root = tk.Tk()
root.title('Quoter')
  
# function that will get the data
# from the API
def get_quote():
    # API request
    r = requests.get('https://api.quotable.io/random')
    data = r.json()
    quote = data['content']
      
    # deletes all the text that is currently
    # in the TextBox
    text_box.delete('1.0', END)
      
    # inserts new data into the TextBox
    text_box.insert(END, quote)
  
  
text_box = Text(root, height=10, width=50)
get_button = Button(root, text="Get Quote", command=get_quote)
  
text_box.pack()
get_button.pack()
root.mainloop()


Output:

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

 

Clicking the button would generate a new quote:

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

 



Previous Article
Next Article

Similar Reads

Difference Between The Widgets Of Tkinter And Tkinter.Ttk In Python
Python offers a variety of GUI (Graphical User Interface) frameworks to develop desktop applications. Among these, Tkinter is the standard Python interface to the Tk GUI toolkit. Tkinter also includes the 'ttk' module, which enhances the visual appeal and functionality of the applications. In this article, we will cover the differences, providing a
4 min read
How to return a JSON response from a Flask API ?
Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Representational State Transfer and is an architectural sty
3 min read
Check If API Response is Empty in Python
In Python programming, determining whether an API response is empty holds importance for effective data handling. This article delves into concise techniques for checking whether the API response is empty or not, enabling developers to efficiently get rid of several data problems and enabling proper error handling. Through clear code examples, let'
2 min read
Open a new Window with a button in Python-Tkinter
Python provides a variety of GUI (Graphic User Interface) such as PyQt, Tkinter, Kivy and soon. Among them, tkinter is the most commonly used GUI module in Python since it is simple and easy to learn and implement as well. The word Tkinter comes from the tk interface. The tkinter module is available in Python standard library.Note: For more informa
3 min read
Create a GUI to Get Domain Information Using Tkinter
Prerequisites: Python GUI – tkinter Domain information is very important for every user. It contains information like Name, organization, State, city, Ip address, emails, server name, etc. In this article, we will write code for getting domain information and bind it with GUI Application. We will use the Python-whois module to get information about
2 min read
How to Get the Tkinter Label Text?
Prerequisite: Python GUI – Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating
2 min read
How to Get the Input From Tkinter Text Box?
Tkinter Text box widget is used to insert multi-line text. This widget can be used for messaging, displaying information, and many other tasks. The important task is to get the inserted text for further processing. For this, we have to use the get() method for the textbox widget. Syntax: get(start, [end]) where, start is starting index of required
1 min read
Get Silver and Gold Price in Tkinter Using Python
Prerequisite: BeautifulSoup, requests, tkinter, datetime In this article, we are going to discuss how to get Gold and Silver Price in India Using Python in Tkinter. There is a variation in price with time to time, price of gold and silver is moved by a combination of supply, demand, and investor behavior. We will use goodreturns website for fetchin
4 min read
How to get selected value from listbox in tkinter?
Prerequisites: Tkinter, Listbox ListBox is one of the many useful widgets provided by Tkinter for GUI development. The Listbox widget is used to display a list of items from which a user can select one or more items according to the constraints. In this article, we'll see how we can get the selected value(s) from a Listbox widget. Code: C/C++ Code
2 min read
How to get the index of selected option in Tkinter Combobox?
In this article, we will be discussing how to get the index of the selected options in the Tkinter Combobox. A Combobox is a combination of a Listbox and an Entry widget. This widget allows users to select one value from a set of values. Syntax: def get_index(*arg): Label(app, text="The value at index " + str(combo.current()) +\ " is" + " " + str(v
3 min read
Article Tags :
Practice Tags :