Create a GUI for weather forecast using weatherstack API in python


What is the need for weather forecast?

Weather forecasting is an essential aspect of human existence. In recent times, technological advancements have made it easier to predict weather with high accuracy. openweathermap is a popular API that allows developers to retrieve weather data. In this tutorial, we will create a graphical user interface (GUI) for weather forecast using openweathermap API in Python. This tutorial will cover the necessary steps for building a GUI and retrieving data from openweathermap API.

Prerequisites

Before we dive into the task few things should is expected to be installed onto your system −

List of recommended settings −

  • pip install tkinter

  • It is expected that the user will have access to any standalone IDE such as VS-Code, PyCharm, Atom or Sublime text.

  • Even online Python compilers can also be used such as Kaggle.com, Google Cloud platform or any other will do.

  • Updated version of Python. At the time of writing the article I have used 3.10.9 version.

  • Knowledge of the use of Jupyter notebook.

  • Knowledge and application of virtual environment would be beneficial but not required.

  • It is also expected that the person will have a good understanding of statistics and mathematics.

Steps required to accomplish the task

Step 1: Import the necessary modules

import tkinter as tk
import requests

The tkinter module is used to create the GUI window, labels, and entry fields. The requests module is used to make API requests to the weatherstack API.

Step 2: Set your weatherstack API key

API_KEY = "your_weatherstack_api_key"

Replace your_weatherstack_api_key with your actual API key.

Step 3: Define the URL for the weatherstack API

API_URL = "http://api.weatherstack.com/current"

This is the URL that will be used to make requests to the weatherstack API.

Step 4: Define the GUI Window

root = tk.Tk()
root.title("Weather Forecast")

This creates the main window of the GUI and sets its title to "Weather Forecast".

Step 5: Define the labels and entry fields for the city and country

city_label = tk.Label(root, text="City:")
city_label.grid(row=0, column=0, padx=5, pady=5)

city_entry = tk.Entry(root)
city_entry.grid(row=0, column=1, padx=5, pady=5)

country_label = tk.Label(root, text="Country:")
country_label.grid(row=1, column=0, padx=5, pady=5)

country_entry = tk.Entry(root)
country_entry.grid(row=1, column=1, padx=5, pady=5)

These create the labels and entry fields for the user to input the city and country they want to get weather data for.

Step 6: Define the function to get the weather data from the API

def get_weather():
   city = city_entry.get()
   country = country_entry.get()
   # Build the URL with the API key, city, and country
   url = f"{API_URL}?access_key={API_KEY}&query={city},{country}"
   # Make the API request and get the JSON response
   response = requests.get(url).json()
   # Extract the relevant weather data from the JSON response
   temperature = response["current"]["temperature"]
   weather_desc = response["current"]["weather_descriptions"][0]
   # Display the weather data in the GUI
   temperature_label.config(text=f"Temperature: {temperature}°C")
   weather_desc_label.config(text=f"Weather Description: {weather_desc}")

This function gets the city and country from the entry fields, builds the API request URL with the API key, city, and country, makes the API request, and extracts the relevant weather data from the JSON response. It then displays the temperature and weather description in the corresponding labels in the GUI.

Step 7: Define the button to get the weather data

get_weather_button = tk.Button(root, text="Get Weather", command=get_weather)
get_weather_button.grid(row=2, column=0, columnspan=2, padx=5, pady=5)

This creates a button that calls the get_weather function when clicked.

Step 8: Define the labels to display the weather data

temperature_label = tk.Label(root, text="")
temperature_label.grid(row=3, column=0, columnspan=2, padx=5, pady=5)

weather_desc_label = tk.Label(root, text="")
weather_desc_label.grid(row=4, column=0, columnspan=2, padx=5, pady=5)

These create the labels that will display the temperature and weather description.

Step 9: Run the GUI window

root.mainloop()

This starts the GUI and keeps it as long as the user wants it to be.

Final code, program

import tkinter as tk
import requests

# Set your weatherstack API key here
API_KEY = "your_weatherstack_api_key"

# Define the URL for the weatherstack API
API_URL = "http://api.weatherstack.com/current"

# Define the GUI window
root = tk.Tk()
root.title("Weather Forecast")

# Define the labels and entry fields for the city and country
city_label = tk.Label(root, text="City:")
city_label.grid(row=0, column=0, padx=5, pady=5)

city_entry = tk.Entry(root)
city_entry.grid(row=0, column=1, padx=5, pady=5)

country_label = tk.Label(root, text="Country:")
country_label.grid(row=1, column=0, padx=5, pady=5)

country_entry = tk.Entry(root)
country_entry.grid(row=1, column=1, padx=5, pady=5)

# Define the function to get the weather data from the API
def get_weather():
   city = city_entry.get()
   country = country_entry.get()
   # Build the URL with the API key, city, and country
   url = f"{API_URL}?access_key={API_KEY}&query={city},{country}"
   # Make the API request and get the JSON response
   response = requests.get(url).json()
   # Extract the relevant weather data from the JSON response
   temperature = response["current"]["temperature"]
   weather_desc = response["current"]["weather_descriptions"][0]
   # Display the weather data in the GUI
   temperature_label.config(text=f"Temperature: {temperature}°C")
   weather_desc_label.config(text=f"Weather Description: {weather_desc}")

# Define the button to get the weather data
get_weather_button = tk.Button(root, text="Get Weather", command=get_weather)
get_weather_button.grid(row=2, column=0, columnspan=2, padx=5, pady=5)

# Define the labels to display the weather data
temperature_label = tk.Label(root, text="")
temperature_label.grid(row=3, column=0, columnspan=2, padx=5, pady=5)

weather_desc_label = tk.Label(root, text="")
weather_desc_label.grid(row=4, column=0, columnspan=2, padx=5, pady=5)

# Run the GUI window
root.mainloop()

In this example, we first import the necessary libraries: tkinter and requests. We then set our weatherstack API key and define the API URL. We create a GUI window using the tk.Tk() function and set the window title.

We create two labels and two entry fields for the city and country using the tk.Label() and tk.Entry() functions. We then define a function called get_weather() that gets the weather data from the API and displays it in the GUI. The function uses the requests.get() function to make a GET request to the API URL with the city and country from the entry fields. It then extracts the temperature and weather description data from the JSON response and updates the temperature and weather description labels in the GUI.

We create a button to get the weather data using the tk.Button() function with the command parameter set to the get_weather() function. We also create two labels to display the temperature and weather description data.

Finally, we run the GUI window using the root.mainloop() function. When the user enters a city and country and clicks the "Get Weather" button, the get_weather() function will make a request to the

Output

This picture shows the output of the weather app GUI after we have entered the name of the city and country. The API key will change based on the user.

Conclusion

In this tutorial, we have learned how to create a GUI for weather forecast using weatherstack API in Python. We have covered the necessary steps for building a GUI and retrieving data from weatherstack API. We have also explained each subsection and provided real-world examples of weather forecast applications that use weatherstack API.

Updated on: 20-Apr-2023

653 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements