Get an API Key from OpenWeather
import tkinter as tk
from tkinter import messagebox
import requests
# OpenWeather API Key (Replace with your own key)
API_KEY = "YOUR_OPENWEATHER_API_KEY"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
# Function to fetch weather data
def get_weather():
city = city_entry.get()
if not city:
messagebox.showerror("Error", "Please enter a city name!")
return
params = {"q": city, "appid": API_KEY, "units": "metric"}
response = requests.get(BASE_URL, params=params)
if response.status_code == 200:
data = response.json()
weather = data["weather"][0]["description"].capitalize()
temp = data["main"]["temp"]
humidity = data["main"]["humidity"]
result_label.config(text=f"š City: {city}\nš”️ Temperature: {temp}°C\nš§ Humidity: {humidity}%\n☁️ Condition: {weather}")
else:
messagebox.showerror("Error", "City not found! Please try again.")
# GUI setup
root = tk.Tk()
root.title("Real-Time Weather Dashboard")
root.geometry("400x350")
tk.Label(root, text="Enter City Name:", font=("Arial", 14)).pack(pady=10)
city_entry = tk.Entry(root, font=("Arial", 12), width=25)
city_entry.pack(pady=5)
tk.Button(root, text="Get Weather", font=("Arial", 12), command=get_weather).pack(pady=10)
result_label = tk.Label(root, text="", font=("Arial", 14), justify="left")
result_label.pack(pady=20)
# Run GUI
root.mainloop()
No comments:
Post a Comment