Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 12, 2023 03:23 pm GMT

Creating a GUI Weather App with Tkinter and OpenWeatherMap API

Hey guys, This short article provides a sample Python code that uses the Tkinter library to create a graphical user interface (GUI) for a weather app. The app allows users to enter a city name and retrieve weather information for that city from the OpenWeatherMap API. The GUI includes a background gradient image, a text entry field for the city name, and a button to retrieve the weather information.

code:

import tkinter as tkfrom tkinter import messageboximport requestsfrom PIL import Image, ImageTkdef get_weather():    city = city_entry.get()    api_key = "your api key" #go to openweather     url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"    # Show loading state    weather_label.config(text="Loading...")    icon_label.config(image='')    response = requests.get(url)    weather_data = response.json()    if "message" in weather_data:        messagebox.showerror("Error", weather_data["message"])    else:        weather_text = f"City: {city}
" weather_text += f"Temperature: {weather_data['main']['temp']}F
" weather_text += f"Pressure: {weather_data['main']['pressure']} hPa
" weather_text += f"Humidity: {weather_data['main']['humidity']}%
" weather_text += f"Min Temp: {weather_data['main']['temp_min']}F
" weather_text += f"Max Temp: {weather_data['main']['temp_max']}F
" weather_text += f"Wind Speed: {weather_data['wind']['speed']} m/s
" weather_text += f"Description: {weather_data['weather'][0]['description']}
" weather_text += f"Sunrise: {weather_data['sys']['sunrise']}
" weather_text += f"Sunset: {weather_data['sys']['sunset']}
" weather_label.config(text=weather_text) #update icon icon_name = weather_data['weather'][0]['icon'] icon_url = f"http://openweathermap.org/img/wn/{icon_name}@2x.png" icon_data = requests.get(icon_url) with open("icon.png", "wb") as f: f.write(icon_data.content) icon_image = ImageTk.PhotoImage(Image.open("icon.png")) icon_label.config(image=icon_image) icon_label.image = icon_imageroot = tk.Tk()root.title("Weather App")# Create gradient imagegradient = Image.new("RGBA", (1, root.winfo_height()), "#8EC5FC")pixels = gradient.load()for y in range(gradient.size[1]): color = int(y / gradient.size[1] * 255), 140, 255 for x in range(gradient.size[0]): pixels[x, y] = colorgradient = gradient.resize((root.winfo_width(), root.winfo_height()))gradient = ImageTk.PhotoImage(gradient)#Set gradient image as backgroundbg_label = tk.Label(root, image=gradient)bg_label.place(relx=0, rely=0, relheight=1, relwidth=1)# Frameframe = tk.Frame(root, bg='#80c1ff', bd=5)frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')# Entrycity_entry = tk.Entry(frame, font=("Courier", 14))city_entry.place(relwidth=0.65, relheight=1)city_entry.insert(0, "Washington D.C.")# Get Weather buttonget_weather_button = tk.Button(frame, text="Get Weather", font=("Courier", 12), command=get_weather)get_weather_button.place(relx=0.7, relwidth=0.3, relheight=1)# Weather labelweather_frame = tk.Frame(root, bg='#80c1ff', bd=10)weather_frame.place(relx=0.5, rely=0.3, relwidth=0.75, relheight=0.5, anchor='n')weather_label = tk.Label(weather_frame, font=("Courier", 14), justify='left', bd=5)weather_label.place(relwidth=1, relheight=1)# Weather iconicon_frame = tk.Frame(weather_frame, bg='#80c1ff')icon_label = tk.Label(icon_frame)icon_label.place(relx=0.5, rely=0.5, anchor='center')icon_frame.place(relx=0.8, rely=0.3, relwidth=0.2, relheight=0.4, anchor='n')root.mainloop()

output:

weather app using python and tkinter

The code starts by importing the necessary libraries, including Tkinter, messagebox, requests, and PIL. The get_weather() function is defined next, which is called when the user clicks the "Get Weather" button. The function first retrieves the city name from the text entry field and constructs the URL for the OpenWeatherMap API request. It then sends the request and retrieves the weather data in the form of a JSON object.

If the response includes an error message, the code shows an error message dialog box. Otherwise, it parses the JSON data to extract the weather information and displays it in a label on the GUI. The code also retrieves the weather icon from the OpenWeatherMap API and displays it on the GUI.

The remaining code creates the GUI elements, including the background gradient image, frame, entry field, and buttons. The resulting weather app provides a simple and easy-to-use interface for retrieving weather information for a given city.


Original Link: https://dev.to/ashishpandey/creating-a-gui-weather-app-with-tkinter-and-openweathermap-api-3oog

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To