Advertisement
CodeCrusader

GUI Weather App

Jun 10th, 2023
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | Software | 0 0
  1. import tkinter as tk
  2. import requests
  3.  
  4. # Initialize the window
  5. window = tk.Tk()
  6. window.title("Weather Application")
  7.  
  8. # Variable
  9. YOUR_API_KEY = "PUT YOUR API KEY FOR OPENWEATHERMAP HERE"
  10.  
  11. # Function to fetch weather information
  12. def get_weather():
  13.     city = entry.get()
  14.     if city:
  15.         url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={YOUR_API_KEY}"
  16.  
  17.         try:
  18.             response = requests.get(url)
  19.             weather_data = response.json()
  20.  
  21.             if weather_data["cod"] == 200:
  22.                 weather_info = weather_data["weather"][0]["description"]
  23.                 temperature = weather_data["main"]["temp"]
  24.                 temperature = round(temperature - 273.15, 2)  # Convert to Celsius
  25.                 humidity = weather_data["main"]["humidity"]
  26.  
  27.                 result_label.config(text=f"Weather: {weather_info}\nTemperature: {temperature} °C\nHumidity: {humidity}%")
  28.             else:
  29.                 result_label.config(text="City not found")
  30.         except requests.exceptions.RequestException:
  31.             result_label.config(text="Failed to fetch weather data")
  32.     else:
  33.         result_label.config(text="Please enter a city")
  34.  
  35. # Entry widget to input city
  36. entry = tk.Entry(window, width=30)
  37. entry.grid(row=0, column=0, padx=10, pady=10)
  38.  
  39. # Button to fetch weather
  40. weather_button = tk.Button(window, text="Get Weather", command=get_weather)
  41. weather_button.grid(row=0, column=1, padx=5)
  42.  
  43. # Label to display weather information
  44. result_label = tk.Label(window, text="")
  45. result_label.grid(row=1, column=0, columnspan=2, padx=10, pady=10)
  46.  
  47. window.mainloop()
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement