Building a Modern Weather App in Python

How to build a Modern Weather App in Python

Building a Modern Weather App in Python

One of the best ways to learn Python desktop development is by building a real-world project. And what could be more useful than a Weather App? It’s simple enough for beginners but also teaches you important concepts like APIs, JSON data, and user interface design.

In this tutorial, we’ll build a desktop weather application in Python using the Tkinter GUI library and the OpenWeatherMap API. By the end, you’ll have a working app that fetches live weather data for any city.

🛠 What You’ll Learn

How to design a desktop UI with Tkinter.

How to use an API to fetch real-time data.

How to parse JSON responses in Python.

How to package your Python app into an executable file.

🌍 Step 1: Understanding the Tools

Before jumping into code, let’s quickly introduce the tools:

Tkinter – Python’s built-in GUI framework. It’s lightweight, beginner-friendly, and requires no extra installation.

Requests – A popular Python library for making HTTP requests. Perfect for connecting to APIs.

OpenWeatherMap API – A free weather API that provides current weather, forecasts, and historical data.

You’ll need to sign up at OpenWeatherMap

 to get a free API key. This key will allow your app to make requests and receive weather data.

⚙ Step 2: Installing Dependencies

First, make sure you have the requests library installed. Run this command:

pip install requests
Tkinter comes built-in with Python, so no installation is needed. 

🖥 Step 3: Setting Up the Project 

Let’s start with a basic Tkinter window:
import tkinter as tk

root = tk.Tk()
root.title("Weather App")
root.geometry("400x300")
root.resizable(False, False)

root.mainloop()
When you run this, you’ll see an empty window. That’s the foundation of our app.

🌤 Step 4: Connecting to the Weather API

Now, let’s write a function to fetch weather data.
import requests

API_KEY = "your_api_key_here"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather?"

def get_weather(city):
    url = BASE_URL + "appid=" + API_KEY + "&q=" + city + "&units=metric"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        main = data['main']
        temp = main['temp']
        humidity = main['humidity']
        weather_desc = data['weather'][0]['description']
        
        result = (f"City: {city}\n"
                  f"Temperature: {temp}°C\n"
                  f"Humidity: {humidity}%\n"
                  f"Condition: {weather_desc.capitalize()}")
    else:
        result = "City not found!"
    return result

🎨 Step 5: Designing the User Interface

Let’s add a text field, a button, and a label to display results.
def show_weather():
    city = city_entry.get()
    weather_info = get_weather(city)
    result_label.config(text=weather_info)

# City input
city_entry = tk.Entry(root, font=("Arial", 14))
city_entry.pack(pady=10)

# Search button
search_btn = tk.Button(root, text="Get Weather", command=show_weather, font=("Arial", 12))
search_btn.pack(pady=10)

# Result display
result_label = tk.Label(root, text="", font=("Arial", 12), justify="left")
result_label.pack(pady=20)
Now, when you type a city and click “Get Weather,” the app will display real-time weather data.

🖌 Step 6: Making It Look Modern

By default, Tkinter apps look plain. Let’s improve it with colors and layout:
root.configure(bg="#1e1e2f")

city_entry.configure(bg="#2e2e3e", fg="white", insertbackground="white")
search_btn.configure(bg="#4e8ef7", fg="white", relief="flat")
result_label.configure(bg="#1e1e2f", fg="white")

📦 Step 7: Packaging the App

You can share your app by packaging it into an executable:
pip install pyinstaller
pyinstaller --onefile weather_app.py

Final Full code:

import tkinter as tk
import requests

# Replace with your OpenWeatherMap API key
API_KEY = "c3bf4e86c509402d0b0f4ef5d91d738d"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather?"

# Function to fetch weather
def get_weather(city):
    url = BASE_URL + "appid=" + API_KEY + "&q=" + city + "&units=metric"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        main = data['main']
        temp = main['temp']
        pressure = main['pressure']
        humidity = main['humidity']
        weather_desc = data['weather'][0]['description']

        result = (f"City: {city}\n"
                  f"Temperature: {temp}°C\n"
                  f"Pressure: {pressure} hPa\n"
                  f"Humidity: {humidity}%\n"
                  f"Condition: {weather_desc.capitalize()}")
    else:
        result = "City not found!"
    return result

# Function for button click
def show_weather():
    city = city_entry.get()
    if city:
        weather_info = get_weather(city)
        result_label.config(text=weather_info)
    else:
        result_label.config(text="Please enter a city name!")

# GUI setup
root = tk.Tk()
root.title("Weather App")
root.geometry("400x300")
root.resizable(False, False)

# Heading
heading = tk.Label(root, text="Weather App", font=("Arial", 18, "bold"))
heading.pack(pady=10)

# City entry
city_entry = tk.Entry(root, font=("Arial", 14))
city_entry.pack(pady=10)

# Button
search_btn = tk.Button(root, text="Get Weather", font=("Arial", 12), command=show_weather)
search_btn.pack(pady=5)

# Result display
result_label = tk.Label(root, text="", font=("Arial", 12), justify="left")
result_label.pack(pady=20)

# Run the app
root.mainloop()

Output Screenshot:

Modern Weather App in Python Screenshot

Frequently Asked Questions (FAQ)

Is Tkinter good for building desktop apps?

Yes. Tkinter is beginner-friendly, included with Python, and ideal for lightweight desktop apps such as a weather app, calculator, or notes app. For more modern UIs you can explore libraries like customtkinter, Kivy, or Flet.

Do I need to pay for the OpenWeatherMap API?

No. OpenWeatherMap offers a free tier that works well for learning and small projects. If your app needs higher request limits or advanced data (historic, bulk), you can upgrade to a paid plan.

Why is my app not showing weather data?

Common reasons:

  • Your API key is missing, invalid, or restricted.
  • The city name is misspelled or not found by the API.
  • Network connectivity issues or the API endpoint is unreachable.
  • You exceeded free-tier rate limits.

Check the response status code and any error message in the API response for debugging.

Can I run this Tkinter app on Android or the Web?

Tkinter is designed for desktop (Windows, macOS, Linux). For mobile or web apps consider:

  • Mobile: Kivy or BeeWare.
  • Web: Use web frameworks or tools like Streamlit (for quick dashboards) or build a frontend with JavaScript and call a Python backend (Flask/FastAPI).
How can I show weather icons (sun, cloud, rain) in the app?

Use the weather icon code from the API response (e.g., data['weather'][0]['icon']). Download or request the corresponding icon from OpenWeatherMap and display it in Tkinter using PhotoImage (for GIF/PNG) or Pillow (PIL.ImageTk.PhotoImage) for broader format support.

How do I package the app so others can run it?

Use PyInstaller to create a single executable:

pip install pyinstaller
pyinstaller --onefile weather_app.py

The executable will be created in the dist/ folder. Test on the target OS and include any extra resource files (icons, config) as needed.

Previous Post Next Post

Contact Form