In this fast-paced world, staying updated with the latest news is crucial. Build your very own News application that gets you news across different categories such as entertainment, sports, and technology accessible on any platform right at your fingertips.
You will develop this application using Tkinter, the standard GUI library for Python, and power it using the News API that gets articles from more than 80,000 sources.
Install tkinter and requests Modules
Tkinter is a cross-platform, simple, and user-friendly module that you can use to create graphical user interfaces rapidly. Some of the applications you can build using Tkinter include a music player, calendar, weight conversion tool, word jumble game, and so on.
To install tkinter in your system, run the following command in the terminal:
pip install tkinter
The requests module makes it easier to make HTTP requests. With this, you can develop interesting applications such as a website status checker, web scraper, stock market monitor bot, and website performance tester. To install the requests module, open the terminal and run the following command:
pip install requests
You can find the entire source code of the News application using Python in this GitHub repository.
Generate the News API Key
Begin by importing the required libraries. Signup at News API and generate your API key. With the free developer account, you can send up to 100 requests daily, which is great to test and get started. Store the API in a variable that you will use later with the base URL to fetch the top headlines according to your country.
from tkinter import *
from tkinter import messagebox
import requests
apiKey = 'YOUR_API_KEY'
Define the Structure of the App
Define a class, NewsApp. Reference the apiKey and type variables globally. Define an object of the class and initialize the root window. Set the dimensions and title of your application. Define two lists, you will use the first list to define the buttons and the second to define to categories of news you want to display in your application.
class NewsApp:
global apiKey, type
def __init__(self, root):
self.root = root
self.root.geometry('1000x650')
self.root.title("News Application")
self.newsCategoryButton = []
self.newsCategory = ["general", "entertainment", "sports", "technology"]
Define a label that acts as a title to your application. Pass the parent element you want to place it in, the text it should display, the font style, the padding, and the background color it should have. Use the pack() fill option to make the label occupy the entire space in the X direction.
Define a LabelFrame and set its parent element along with the background color it should possess. Use the place() function to organize it at specified coordinates. Additionally, pass the width and height of the frame.
title = Label(self.root, text="News Application", font=("times new roman", 28, "bold"), pady=2, bg='#ff007f').pack(fill=X)
F1 = LabelFrame(self.root, bg='#fc6c85')
F1.place(x=20, y=80, width=215, height=210)
Define a for loop that runs through the length of the newsCat list. Define a button in the frame defined earlier. Pass the text it should display and convert it into uppercase. Pass the width, the border depth, the font style, and the background color of the buttons. Use the grid manager to arrange the buttons in a columnar format and add padding in the X and Y directions.
Use the bind method to attach the button and the news area. <Button-1> defines that the Newsarea function will occur on the left mouse click by the user. Append these buttons to the newsCatButton list defined earlier.
for i in range(len(self.newsCategory)):
b = Button(F1, text=self.newsCategory[i].upper(), width=15, bd=3, font="arial 14 bold", bg='#c154c1')
b.grid(row=i, column=0, padx=10, pady=5)
b.bind('<Button-1>', self.Newsarea)
self.newsCategoryButton.append(b)
Define a frame and pass it the parent element you want to place it in and the border depth it should have. Organize it at specified coordinates and pass the relative height and width. Define a vertical scrollbar using the orient parameter and place it in this frame.
Define a text widget. Pass the parent element as this frame along with the font style and the background color it should possess. On setting the value of the yscrollcommand as scroll_y.set it gets the current position of the scrollbar on user interaction.
F2 = Frame(self.root, bd=3)
F2.place(x=260, y=80, relwidth=0.7, relheight=0.8)
scroll_y = Scrollbar(F2, orient=VERTICAL)
self.txtarea = Text(F2, yscrollcommand=scroll_y.set, font=("times new roman", 15, "bold"), bg='#fc6c85')
Use the pack() fill option to place the scrollbar on the right side of the frame and occupy the entire space in the Y direction. On setting the command parameter as txtarea.yview, the scrollbar's movement gets linked to the up and down functions. So, when the user interacts with the scrollbar, the text area's views change accordingly.
Use the insert() method to ask the user to select a category and place it at the end of any existing text. Use the pack() method to ask the text widget to take the space in the X and Y direction and assign additional space if necessary using the expand parameter.
scroll_y.pack(side=RIGHT, fill=Y)
scroll_y.config(command=self.txtarea.yview)
self.txtarea.insert(END,"Select a category:")
self.txtarea.pack(fill=BOTH, expand=1)
Extract News From the API Response
Define a function, Newsarea() that accepts the current instance of the class and the button event. Pass the category of the news the user selected in lowercase and store it. Pass the required parameters to the base URL and delete any text present earlier from the first index to the last one. Insert a line for demarcation.
Define a try block and send an HTTP GET request to the server defined in the base URL. Convert the response into JSON format and extract the contents that have the key as articles and store it in a variable.
def Newsarea(self, event):
type = event.widget.cget('text').lower()
BASE_URL = f'http://newsapi.org/v2/top-headlines?country=in&category={type}&apiKey=' + apiKey
self.txtarea.delete("1.0", END)
self.txtarea.insert(END, "--------------------------------------------------------------------\n")
try:
articles = (requests.get(BASE_URL).json())['articles']
If the number of articles fetched is not zero, run a loop and insert the articles one by one in the text widget. Display the title, followed by the description, content, and URL in separate lines. Insert two lines for demarcation. If the number of articles is zero, display that no news is available for that particular category.
If the try block fails, use the exception block to display the appropriate error message to the users.
if (articles != 0):
for i in range(len(articles)):
self.txtarea.insert(END, f"{articles[i]['title']}\n")
self.txtarea.insert(END, f"{articles[i]['description']}\n")
self.txtarea.insert(END, f"{articles[i]['content']}\n")
self.txtarea.insert(END, f"read more...{articles[i]['url']}\n")
self.txtarea.insert(END, "-------------------------------------------------------------\n")
self.txtarea.insert(END, "-------------------------------------------------------------\n")
else:
self.txtarea.insert(END, "No news available")
except Exception as e:
messagebox.showerror('ERROR', "Sorry, we ran into some issues. Please check the internet connection and try again.")
Create an instance of the class and initialize it. The mainloop() function tells Python to run the Tkinter event loop and listen for events until you close the window.
root = Tk()
obj = NewsApp(root)
root.mainloop()
Put all the code together and your application is ready to display news according to different categories.
The Output of the News Application
On running the program, the text area asks to select a category. On clicking any of the buttons, it displays the news with the description, content, and its link (if present) for that category separated by two lines.
Useful APIs for Your Python Project
APIs are super handy to integrate new applications with existing software systems. You can use the OpenWeatherMap API to retrieve real-time weather information of any area and Google Maps API to incorporate maps into your website application. You can automate GitHub tasks via the GitHub API and use Zoom API for integrating video conferencing.
You can also use the power of ChatGPT from within your own apps using OpenAI’s API and create some fascinating AI-powered applications.