5 Best Ways to Create a GUI for Weather Forecast Using WeatherStack API in Python

πŸ’‘ Problem Formulation:

In this article, we address the specific issue of creating a user interface in Python to display weather forecasts using the WeatherStack API. The input is a location query from the user, and the desired output is a graphical presentation of weather information such as temperature, wind speed, and forecasts.

Method 1: Using Tkinter for Desktop Applications

Tkinter is Python’s de-facto standard GUI package and is an excellent option for creating a simple desktop application for weather forecasting. By integrating Tkinter with the WeatherStack API, we can fetch real-time weather data and display it in a window on the user’s desktop.

Here’s an example:

import tkinter as tk
import requests

def get_weather_data():
    api_key = 'YOUR_API_KEY'
    city = city_entry.get()
    url = f"http://api.weatherstack.com/current?access_key={api_key}&query={city}"
    response = requests.get(url)
    weather_data = response.json()
    weather_label.config(text=str(weather_data))

root = tk.Tk()
city_entry = tk.Entry(root)
city_entry.pack()
get_weather_button = tk.Button(root, text="Get Weather", command=get_weather_data)
get_weather_button.pack()
weather_label = tk.Label(root, text="")
weather_label.pack()
root.mainloop()

The output is a GUI window where the user can enter a city name, click “Get Weather”, and receive real-time weather data.

In this code snippet, we import Tkinter and requests modules, set up a basic UI with an entry widget to take the user’s city input, a button to trigger the API call, and a label to display the weather data. The get_weather_data function constructs the API request, sends it using the requests library, and updates the label with the obtained data.

Method 2: Building a GUI with PyQt

PyQt is a set of Python bindings for the Qt application framework that enables you to create cross-platform applications with native GUI performance. When utilized with the WeatherStack API, PyQt provides advanced UI features and customization.

Here’s an example:

from PyQt5 import QtWidgets, QtCore
import sys
import requests

class WeatherApp(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    
    def initUI(self):
        self.city_entry = QtWidgets.QLineEdit(self)
        self.get_weather_button = QtWidgets.QPushButton('Get Weather', self)
        self.get_weather_button.clicked.connect(self.getWeather)
        self.weather_label = QtWidgets.QLabel('', self)
        
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.city_entry)
        layout.addWidget(self.get_weather_button)
        layout.addWidget(self.weather_label)
        
        self.show()

    def getWeather(self):
        api_key = 'YOUR_API_KEY'
        city = self.city_entry.text()
        url = f"http://api.weatherstack.com/current?access_key={api_key}&query={city}"
        response = requests.get(url)
        weather_data = response.json()
        self.weather_label.setText(str(weather_data['current']['temperature']) + 'Β°C')

app = QtWidgets.QApplication(sys.argv)
ex = WeatherApp()
sys.exit(app.exec_())

The output is a more modern GUI window allowing the user to input a city and get the temperature displayed.

This code sets up a PyQt widget with QLineEdit, QPushButton, and QLabel. The getWeather method gets the text from the QLineEdit, sends a request with the city to the WeatherStack API, and updates the QLabel with the current temperature. PyQt applications support theming and a wide range of widgets.

Method 3: Using Kivy for Touch-Friendly Applications

Kivy is an open-source Python library used for developing multitouch applications. It is well-suited for weather forecast applications as it can be run on Android, iOS, Linux, OS X, and Windows with the same codebase.

Here’s an example:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
import requests

class WeatherApp(App):
    def build(self):
        layout = BoxLayout(orientation='vertical')
        self.city_input = TextInput(text='', multiline=False)
        self.get_weather_button = Button(text='Get Weather')
        self.get_weather_button.bind(on_press=self.get_weather)
        self.weather_info = Label(text='')
        layout.add_widget(self.city_input)
        layout.add_widget(self.get_weather_button)
        layout.add_widget(self.weather_info)
        return layout

    def get_weather(self, instance):
        api_key = 'YOUR_API_KEY'
        city = self.city_input.text
        url = f"http://api.weatherstack.com/current?access_key={api_key}&query={city}"
        response = requests.get(url)
        weather_data = response.json()
        self.weather_info.text = 'Temperature: ' + str(weather_data['current']['temperature'])

if __name__ == '__main__':
    WeatherApp().run()

The output is a touch-friendly GUI application that displays the temperature for the input city.

This Kivy application demonstrates the use of a BoxLayout, a TextInput for the city input, a Button and a Label. The get_weather method binds to the button’s press event, sends an API request and updates the label with the weather information.

Method 4: Web GUI using Flask

Flask is a lightweight WSGI web application framework. It allows you to establish a server that can be accessed via a web browser on various devices. When integrated with the WeatherStack API, it serves weather data on a web page.

Here’s an example:

from flask import Flask, render_template, request
import requests

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    weather_data = ''
    if request.method == 'POST':
        city = request.form['city']
        api_key = 'YOUR_API_KEY'
        url = f"http://api.weatherstack.com/current?access_key={api_key}&query={city}"
        response = requests.get(url)
        weather_data = response.json()['current']
    return render_template('index.html', weather_data=weather_data)

if __name__ == '__main__':
    app.run(debug=True)

The output is a website that takes a city as input and displays the weather forecast.

This Flask application creates a web server with a form to input a city’s name. Handling a POST request, it communicates with the WeatherStack API and renders the result with the weather data on a web page using templates.

Bonus One-Liner Method 5: Console Output with Rich

Rich is a Python library designed to make CLI output more readable and visually appealing. It can be combined with a simple request to WeatherStack to display weather information in a stylized format on the console.

Here’s an example:

from rich.console import Console
import requests

console = Console()

api_key = 'YOUR_API_KEY'
city = input("Enter city name: ")
url = f"http://api.weatherstack.com/current?access_key={api_key}&query={city}"
response = requests.get(url)
weather_data = response.json()['current']
console.print(f"The weather in {city}: {weather_data['temperature']}Β°C", style="bold green")

The output is a colorful and styled console message showing the temperature of the requested city.

This snippet captures a city input from the console, issues a request to the WeatherStack API, and the Rich library is used to print out a stylized message containing the weather information.

Summary/Discussion

  • Method 1: Tkinter. Strengths: Widely used, part of Python’s standard library, great for simple desktop apps. Weaknesses: Outdated look compared to modern GUIs, less flexible for complex applications.
  • Method 2: PyQt. Strengths: Cross-platform compatibility, supports advanced GUI features, and has a modern look. Weaknesses: Larger package size, learning curve for beginners.
  • Method 3: Kivy. Strengths: Excellent for multitouch applications, cross-platform (including mobile). Weaknesses: Different to standard GUI frameworks, may require more code for advanced features.
  • Method 4: Flask. Strengths: Creates a web-based interface accessible from various devices, easy to expand. Weaknesses: Requires knowledge of web development, not suitable for offline applications.
  • Method 5: Rich Console Output. Strengths: Quick setup, appealing for command-line interface users. Weaknesses: Non-interactive and lacks GUI.