Note - Double Click to Copy Code Contact Us!

Real-Time Weather Forecasting App

Tech Doubility
Real-Time Weather Forecasting App


Python
  1. import tkinter as tk
  2. from tkinter import messagebox
  3. import requests
  4.  
  5. def get_weather():
  6. api_key = 'YOUR_API_KEY'
  7. base_url = 'http://api.openweathermap.org/data/2.5/weather'
  8. city = city_entry.get()
  9.  
  10. if not city:
  11. messagebox.showerror('Error', 'Please enter a city name')
  12. return
  13.  
  14. params = {'q': city, 'appid': api_key, 'units': 'metric'}
  15. response = requests.get(base_url, params=params)
  16. weather_data = response.json()
  17.  
  18. if weather_data['cod'] != '404':
  19. main_info = weather_data['weather'][0]['main']
  20. description = weather_data['weather'][0]['description']
  21. temperature = weather_data['main']['temp']
  22. humidity = weather_data['main']['humidity']
  23. wind_speed = weather_data['wind']['speed']
  24.  
  25. messagebox.showinfo('Weather Forecast', f'Main: {main_info}\n'
  26. f'Description: {description}\n'
  27. f'Temperature: {temperature}°C\n'
  28. f'Humidity: {humidity}%\n'
  29. f'Wind Speed: {wind_speed} m/s')
  30. else:
  31. messagebox.showerror('Error', 'City not found')
  32.  
  33. # Create the main window
  34. root = tk.Tk()
  35. root.title('Weather Forecast')
  36.  
  37. # Create and pack the city entry widget
  38. city_entry = tk.Entry(root)
  39. city_entry.pack()
  40.  
  41. # Create and pack the submit button
  42. submit_button = tk.Button(root, text='Get Weather', command=get_weather)
  43. submit_button.pack()
  44.  
  45. # Run the application
  46. root.mainloop()
  47.  

    Make sure to replace 'YOUR_API_KEY' with your actual OpenWeatherMap API key. You can sign up for a free API key on the OpenWeatherMap website.

    This code creates a simple GUI with a text entry field for the city name and a button to retrieve the weather forecast. When the button is clicked, the get_weather function is called, which sends a request to the OpenWeatherMap API to get the weather information for the specified city. The weather data is then displayed in a message box.

    Note that this code is just a basic example and can be further enhanced and customized according to your needs

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.