Developing a Real-Time Weather Forecast Application with Python and Tkinter GUI

Posted by

Creating a live Weather Forecast Application in Python using Tkinter GUI

Creating a live Weather Forecast Application in Python using Tkinter GUI

If you’re looking to create a simple weather forecast application in Python, using Tkinter for the graphical user interface (GUI), you’ve come to the right place.

Step 1: Install the necessary libraries

Before we can start building our weather forecast application, we need to make sure we have the necessary libraries installed. You’ll need to install Tkinter, a popular GUI library for Python, as well as the requests library, which will allow us to make API calls to get weather data.


pip install tk
pip install requests

Step 2: Create the GUI using Tkinter

Now that we have the necessary libraries installed, we can start creating our GUI using Tkinter. Below is a simple example of how to create a basic weather forecast application with a text input field for the location and a button to fetch the weather data.


import tkinter as tk

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

location_entry = tk.Entry(root)
location_entry.pack()

def fetch_weather():
location = location_entry.get()
# Add code to fetch weather data using API

fetch_button = tk.Button(root, text="Fetch Weather", command=fetch_weather)
fetch_button.pack()

root.mainloop()

Step 3: Fetch weather data using an API

Next, we need to add the code to fetch weather data using an API. You can use a free weather API like OpenWeatherMap to get weather data for a specific location. Below is an example of how to make a HTTP request to the OpenWeatherMap API and parse the JSON response:


import requests

API_KEY = "YOUR_API_KEY_HERE"

def fetch_weather():
location = location_entry.get()
url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={API_KEY}"

response = requests.get(url)
data = response.json()

# Parse the data and display the weather forecast in the GUI

Step 4: Display the weather forecast in the GUI

Finally, we need to parse the weather data we fetched from the API and display it in the GUI. You can display the current temperature, weather description, and any other relevant information in a label or text field.


weather_label = tk.Label(root, text="")
weather_label.pack()

def fetch_weather():
location = location_entry.get()
url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={API_KEY}"

response = requests.get(url)
data = response.json()

temperature = data['main']['temp']
description = data['weather'][0]['description']

weather_label.config(text=f"Temperature: {temperature}°FnDescription: {description}")

And that’s it! You now have a basic weather forecast application in Python using Tkinter GUI. You can further enhance the application by adding more features like a 7-day forecast or a weather map.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Technocratajitsaigal
8 months ago

Program Code:

import tkinter as tk

from tkinter import *

from geopy.geocoders import Nominatim

from timezonefinder import TimezoneFinder

from datetime import datetime

import requests

import pytz

from PIL import Image, ImageTk

root = Tk()

root.title("Live Weather Forecast")

root.geometry("900×600+200+50")

root.resizable(False, False)

def getWeather():

try:

city = textfield.get()

geolocator = Nominatim(user_agent="geoapiExercises")

location = geolocator.geocode(city)

obj = TimezoneFinder()

result = obj.timezone_at(lng=location.longitude, lat=location.latitude)

home = pytz.timezone(result)

local_time = datetime.now(home)

current_time = local_time.strftime("%I:%M %p")

clock.config(text=current_time)

# Weather API

api = (

"https://api.openweathermap.org/data/2.5/weather?q="

+ city

+ "&appid=413bd6cbf6f93b80d6f87ba12e4c3c30"

)

json_data = requests.get(api).json()

condition = json_data["weather"][0]["main"]

description = json_data["weather"][0]["description"]

tempt = int(json_data["main"]["temp"] – 273.15)

feels_like = int(json_data["main"]["feels_like"] – 273.15)

press = json_data["main"]["pressure"]

humid = json_data["main"]["humidity"]

wind_1 = json_data["wind"]["speed"]

country = json_data["sys"]["country"]

#print current time, city, country code

name.config(text="CURRENT TIME: "+city+", "+country)

temp.config(text=(tempt, "°C"))

cond.config(text=(condition, "|", "Feels", "Like", feels_like, "°C"))

wind.config(text=(wind_1, "m/s"))

humidity.config(text=(humid, "g/m3"))

pressure.config(text=(press,"hPa"))

except Exception as e:

messagebox.showerror("Weather App", "Invalid Input!")

# Search Box

Search_image = PhotoImage(file="search.png")

myimage = Label(image=Search_image)

myimage.place(x=220, y=20)

# To clear Default Text content & font format in Search Box when clicked

# Default value of Search Box is "Type Location" in white color

# When clicked, defult value dissapears, font characteristics change

def on_click(event):

textfield.config(foreground='black', font=("Times New Roman", 22, "bold"))

if textfield.get() == "Type Location":

event.widget.delete(0, tk.END)

defaultText = tk.StringVar()

defaultText.set("Type Location")

textfield = tk.Entry(

root,

justify="center",

width=17,

font=("Arial", 24),

bg="#87ceeb",

fg="white",

border=0,

textvariable = defaultText,

)

textfield.place(x=240, y=40)

textfield.bind("<FocusIn>", on_click)

# Search Icon

Search_icon = PhotoImage(file="search_icon.png")

myimage_icon = Button(

image=Search_icon, borderwidth=0, cursor="hand2", bg="#404040", command=getWeather

)

myimage_icon.place(x=520, y=22)

# Time

name = Label(root, font=("Arial", 14, "bold"))

name.place(x=300, y=100)

clock = Label(root, font=("Arial", 18, "bold"), fg="red")

clock.place(x=358, y=130)

# Resizing the image

image = Image.open("logo.png")

resize_image = image.resize((250, 250))

# Logo

Logo_image = ImageTk.PhotoImage(resize_image)

logo = Label(image=Logo_image)

print(logo.size)

logo.place(x=291, y=165)

# Temp and Condition

temp = Label(font=("Times New Roman", 30, "bold"), fg="red")

temp.place(x=385, y=422)

cond = Label(font=("Times New Roman", 16, "bold"))

cond.place(x=315, y=472)

# Bottom Box

Frame_image = PhotoImage(file="box.png")

frame_myimg = Label(image=Frame_image)

frame_myimg.place(x=5, y=300)

frame_myimg.pack(side=BOTTOM)

# Labels

# Label 1

label1 = Label(

root, text="WIND", font=("Calibri", 18, "bold"), fg="white", bg="#1ab5ef"

)

label1.place(x=180, y=510)

# Label 2

label1 = Label(

root, text="HUMIDITY", font=("Calibri", 18, "bold"), fg="white", bg="#1ab5ef"

)

label1.place(x=370, y=510)

# Label 3

label1 = Label(

root, text="PRESSURE", font=("Calibri", 18, "bold"), fg="white", bg="#1ab5ef"

)

label1.place(x=620, y=510)

# Fetched Values

wind = Label(text=" …", font=("Calibri", 14, "bold"), bg="#1ab5ef")

wind.place(x=178, y=545)

humidity = Label(text=" …", font=("Calibri", 14, "bold"), bg="#1ab5ef")

humidity.place(x=390, y=545)

pressure = Label(text=" …", font=("Calibri", 14, "bold"), bg="#1ab5ef")

pressure.place(x=635, y=545)

root.mainloop()

@saigalb9765
8 months ago

Thanks for the code

@frankhardy1016
8 months ago

💯