天气预报应用于Python | Tkinter - GUI

389 阅读6分钟

在本教程中,你将了解到如何在Python中创建一个GUI天气应用程序。它使用Open Weather Map API来获取全球各地城市和地方的最新天气信息。此外,我们将用GUI(图形用户界面)来实现这个天气应用程序,而不是用传统的枯燥的方式,这在CLI(命令行界面)中广泛使用,显示输出。

Python中的天气应用程序代码 - GUI

闲话少说,让我们直接进入代码设置,在Python中创建我们的GUI天气应用程序

1.安装和导入Tkinter

我们首先使用pip软件包管理器安装所需的库。在你的命令行或终端输入以下命令来安装这些模块。

我们需要安装:

  • Request: 用于从API获取数据
  • Tkinter:使我们的天气应用程序基于GUI(图形用户界面)。
  • DateTime:将API中的时间改为不同的格式。
pip install tkinter
pip install datetime
pip install requests
pip install json

从终端安装完所需的库后,我们现在移到我们的Python文件进行编码。我们从导入库开始。

from tkinter import *
import requests
import json
from datetime import datetime

2.初始化Tkinter窗口

作为下一步,我们使用Tkinter模块初始化我们的GUI窗口。

#Initialize Window

root =Tk()
root.geometry("400x400") #size of the window by default
root.resizable(0,0) #to make the window size fixed
#title of our window
root.title("Weather App - AskPython.com")

3.3.OpenWeatherMap API

在我们的代码中,我们将使用Open Weather API(免费层)来获取当前准确和最新的天气信息。

  • 要做到这一点,请到OpenWeatherMap网站创建 一个账户。
  • 创建账户后,进入个人资料,然后进入 "我的API密钥"。
  • 这将打开你的API密钥的网页,复制它以便以后在下一步的代码中使用。

4.天气功能

这里,是我们在代码中添加功能的部分。这一部分对于获得正确的天气信息是最关键的,因为这涉及到从API中获取数据并以准确的格式显示。

我们对这段代码中最重要的功能进行编码,也就是显示天气,我们在代码中这样做。

city_value = StringVar()

def showWeather():

#Enter you api key, copies from the OpenWeatherMap dashboard
    api_key = "eda2b2s6d#sd65f4de7c4b8"  #sample API

    # Get city name from user from the input field (later in the code)
    city_name=city_value.get()

    # API url
    weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key

    # Get the response from fetched url
    response = requests.get(weather_url)

    # changing response from json to python readable 
    weather_info = response.json()


    tfield.delete("1.0", "end")   #to clear the text field for every new output

#as per API documentation, if the cod is 200, it means that weather data was successfully fetched


    if weather_info['cod'] == 200:
        kelvin = 273 # value of kelvin

#-----------Storing the fetched values of weather of a city

        temp = int(weather_info['main']['temp'] - kelvin)                                     #converting default kelvin value to Celcius
        feels_like_temp = int(weather_info['main']['feels_like'] - kelvin)
        pressure = weather_info['main']['pressure']
        humidity = weather_info['main']['humidity']
        wind_speed = weather_info['wind']['speed'] * 3.6
        sunrise = weather_info['sys']['sunrise']
        sunset = weather_info['sys']['sunset']
        timezone = weather_info['timezone']
        cloudy = weather_info['clouds']['all']
        description = weather_info['weather'][0]['description']

        sunrise_time = time_format_for_location(sunrise + timezone)
        sunset_time = time_format_for_location(sunset + timezone)

#assigning Values to our weather varaible, to display as output
        
        weather = f"\nWeather of: {city_name}\nTemperature (Celsius): {temp}°\nFeels like in (Celsius): {feels_like_temp}°\nPressure: {pressure} hPa\nHumidity: {humidity}%\nSunrise at {sunrise_time} and Sunset at {sunset_time}\nCloud: {cloudy}%\nInfo: {description}"
    else:
        weather = f"\n\tWeather for '{city_name}' not found!\n\tKindly Enter valid City Name !!"



    tfield.insert(INSERT, weather)   #to insert or send value in our Text Field to display output

作为添加功能的最后一步,我们添加一个函数来改变时间格式,这个函数检查当地时间与UTC (世界时间协调)的比较,API根据我们的位置给出时间格式的输出。例如:UTC到IST。

def time_format_for_location(utc_with_tz):
    local_time = datetime.utcfromtimestamp(utc_with_tz)
    return local_time.time()

5.编写GUI(前端元素)的代码

我们现在开始为GUI的元素编码,如标题、文本、标签、按钮等。

首先,我们为我们想要的天气的城市名称文本字段编码,同时用标签来表示。

  • 我们使用 Label 方法来生成一个文本标签,以表明城市名称输入字段的目的。
  • Entry 方法用于创建一个输入城市名称的输入字段,以检查其天气。
  • textvaraible部件被用来存储输入的值,在名为:city_value的变量中。
  • 除了这些小部件,我们还通过字体大小、颜色等对我们的代码进行了一些样式设计。
city_head= Label(root, text = 'Enter City Name', font = 'Arial 12 bold').pack(pady=10) #to generate label heading

inp_city = Entry(root, textvariable = city_value,  width = 24, font='Arial 14 bold').pack() #entry field

我们编写了一个 检查天气的按钮,点击它可以检查用户输入的城市的天气。

  • 我们给我们的按钮加上一些样式,以及名称--"检查天气"。我们使用'command'部件,它显示了在点击(按键)按钮时将运行的函数(这里是showWeather 函数),正如上一步所编码的。
Button(root, command = showWeather, text = "Check Weather", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20)

添加完这个后,我们在代码中添加输出元素。我们的天气信息将被显示在这些元素上。

  • 然而,我们再次添加一个标签,在下面的文本框中为我们的结果命名
  • 为了显示输出,我们使用一个文本字段,每当 "检查天气 "按钮被按下时,它就会获得其值。这设想了一个函数来检查处理后从API获取的天气信息,[showWeather函数的输出] 。
weather_now = Label(root, text = "The Weather is: ", font = 'arial 12 bold').pack(pady=10)

tfield = Text(root, width=46, height=10)
tfield.pack()

Python中GUI天气应用程序的最终代码

from tkinter import *
import requests
import json
from datetime import datetime

#Initialize Window

root =Tk()
root.geometry("400x400") #size of the window by default
root.resizable(0,0) #to make the window size fixed
#title of our window
root.title("Weather App - AskPython.com")


# ----------------------Functions to fetch and display weather info
city_value = StringVar()


def time_format_for_location(utc_with_tz):
    local_time = datetime.utcfromtimestamp(utc_with_tz)
    return local_time.time()


city_value = StringVar()

def showWeather():
    #Enter you api key, copies from the OpenWeatherMap dashboard
    api_key = "eda2b2s6d#sd65f4de7c4b8"  #sample API

    # Get city name from user from the input field (later in the code)
    city_name=city_value.get()

    # API url
    weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key

    # Get the response from fetched url
    response = requests.get(weather_url)

    # changing response from json to python readable 
    weather_info = response.json()


    tfield.delete("1.0", "end")   #to clear the text field for every new output

#as per API documentation, if the cod is 200, it means that weather data was successfully fetched


    if weather_info['cod'] == 200:
        kelvin = 273 # value of kelvin

#-----------Storing the fetched values of weather of a city

        temp = int(weather_info['main']['temp'] - kelvin)                                     #converting default kelvin value to Celcius
        feels_like_temp = int(weather_info['main']['feels_like'] - kelvin)
        pressure = weather_info['main']['pressure']
        humidity = weather_info['main']['humidity']
        wind_speed = weather_info['wind']['speed'] * 3.6
        sunrise = weather_info['sys']['sunrise']
        sunset = weather_info['sys']['sunset']
        timezone = weather_info['timezone']
        cloudy = weather_info['clouds']['all']
        description = weather_info['weather'][0]['description']

        sunrise_time = time_format_for_location(sunrise + timezone)
        sunset_time = time_format_for_location(sunset + timezone)

#assigning Values to our weather varaible, to display as output
        
        weather = f"\nWeather of: {city_name}\nTemperature (Celsius): {temp}°\nFeels like in (Celsius): {feels_like_temp}°\nPressure: {pressure} hPa\nHumidity: {humidity}%\nSunrise at {sunrise_time} and Sunset at {sunset_time}\nCloud: {cloudy}%\nInfo: {description}"
    else:
        weather = f"\n\tWeather for '{city_name}' not found!\n\tKindly Enter valid City Name !!"



    tfield.insert(INSERT, weather)   #to insert or send value in our Text Field to display output



#------------------------------Frontend part of code - Interface


city_head= Label(root, text = 'Enter City Name', font = 'Arial 12 bold').pack(pady=10) #to generate label heading

inp_city = Entry(root, textvariable = city_value,  width = 24, font='Arial 14 bold').pack()


Button(root, command = showWeather, text = "Check Weather", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20)

#to show output

weather_now = Label(root, text = "The Weather is:", font = 'arial 12 bold').pack(pady=10)

tfield = Text(root, width=46, height=10)
tfield.pack()

root.mainloop()

总结

本教程到此结束。希望你已经很好地学会了如何在Python中制作一个天气应用程序,而且是通过编码一个基于界面的脚本以及API调用(Open Weather Map)和Tkinter来提高水平的。