Python 使用天气weatherstack API创建天气预报的图形用户界面
天气预报的必要性
天气预报是人类生活中不可或缺的一部分。近年来,技术进步使得天气预报变得更加准确可靠。 openweathermap是一个广受欢迎的API,允许开发者获取天气数据。在本教程中,我们将使用Python以openweathermap API为基础创建一个天气预报的图形用户界面(GUI)。本教程将涵盖构建GUI和从openweathermap API检索数据所需的步骤。
先决条件
在我们开始之前,需要安装一些必要的东西:
推荐的设置清单如下:
- pip install tkinter
-
预计用户可以访问任何独立的IDE,如VS-Code、PyCharm、Atom或Sublime Text。
-
甚至可以使用在线的Python编译器,如Kaggle.com、Google Cloud platform或任何其他可用的编译器。
-
更新版本的Python。在撰写本文时,我使用的是3.10.9版本。
-
使用Jupyter notebook的知识。
-
对虚拟环境的了解和应用将有益但不是必需的。
-
预计个人应对统计学和数学有很好的理解。
完成任务所需的步骤
第1步:导入必要的模块
import tkinter as tk
import requests
tkinter模块用于创建GUI窗口、标签和输入字段。requests模块用于向weatherstack API发出API请求。
第2步:设置您的weatherstack API密钥
API_KEY = "your_weatherstack_api_key"
用您实际的API密钥替换your_weatherstack_api_key。
第3步:定义weatherstack API的URL
API_URL = "http://api.weatherstack.com/current"
这是用来向weatherstack API发送请求的URL。
第4步:定义GUI窗口
root = tk.Tk()
root.title("Weather Forecast")
这将创建GUI的主窗口,并将其标题设置为“天气预报”。
第5步:为城市和国家定义标签和输入字段
city_label = tk.Label(root, text="City:")
city_label.grid(row=0, column=0, padx=5, pady=5)
city_entry = tk.Entry(root)
city_entry.grid(row=0, column=1, padx=5, pady=5)
country_label = tk.Label(root, text="Country:")
country_label.grid(row=1, column=0, padx=5, pady=5)
country_entry = tk.Entry(root)
country_entry.grid(row=1, column=1, padx=5, pady=5)
这些为用户创建了标签和输入字段,以便输入他们想获取天气数据的城市和国家。
第6步:定义从API获取天气数据的函数
def get_weather():
city = city_entry.get()
country = country_entry.get()
# Build the URL with the API key, city, and country
url = f"{API_URL}?access_key={API_KEY}&query={city},{country}"
# Make the API request and get the JSON response
response = requests.get(url).json()
# Extract the relevant weather data from the JSON response
temperature = response["current"]["temperature"]
weather_desc = response["current"]["weather_descriptions"][0]
# Display the weather data in the GUI
temperature_label.config(text=f"Temperature: {temperature}°C")
weather_desc_label.config(text=f"Weather Description: {weather_desc}")
这个函数从输入字段中获取城市和国家,使用API密钥、城市和国家构建API请求URL,发送API请求,并从JSON响应中提取相关的天气数据。然后,它将温度和天气描述显示在GUI中相应的标签中。
第7步:定义获得天气数据的按钮
get_weather_button = tk.Button(root, text="Get Weather", command=get_weather)
get_weather_button.grid(row=2, column=0, columnspan=2, padx=5, pady=5)
这将创建一个按钮,当点击时调用get_weather函数。
第8步:定义用于显示天气数据的标签
temperature_label = tk.Label(root, text="")
temperature_label.grid(row=3, column=0, columnspan=2, padx=5, pady=5)
weather_desc_label = tk.Label(root, text="")
weather_desc_label.grid(row=4, column=0, columnspan=2, padx=5, pady=5)
这些代码会创建用于显示温度和天气描述的标签。
第9步:运行GUI窗口
root.mainloop()
这个代码启动GUI,并保持它的存在,直到用户不再需要它。
最终代码
import tkinter as tk
import requests
# Set your weatherstack API key here
API_KEY = "your_weatherstack_api_key"
# Define the URL for the weatherstack API
API_URL = "http://api.weatherstack.com/current"
# Define the GUI window
root = tk.Tk()
root.title("Weather Forecast")
# Define the labels and entry fields for the city and country
city_label = tk.Label(root, text="City:")
city_label.grid(row=0, column=0, padx=5, pady=5)
city_entry = tk.Entry(root)
city_entry.grid(row=0, column=1, padx=5, pady=5)
country_label = tk.Label(root, text="Country:")
country_label.grid(row=1, column=0, padx=5, pady=5)
country_entry = tk.Entry(root)
country_entry.grid(row=1, column=1, padx=5, pady=5)
# Define the function to get the weather data from the API
def get_weather():
city = city_entry.get()
country = country_entry.get()
# Build the URL with the API key, city, and country
url = f"{API_URL}?access_key={API_KEY}&query={city},{country}"
# Make the API request and get the JSON response
response = requests.get(url).json()
# Extract the relevant weather data from the JSON response
temperature = response["current"]["temperature"]
weather_desc = response["current"]["weather_descriptions"][0]
# Display the weather data in the GUI
temperature_label.config(text=f"Temperature: {temperature}°C")
weather_desc_label.config(text=f"Weather Description: {weather_desc}")
# Define the button to get the weather data
get_weather_button = tk.Button(root, text="Get Weather", command=get_weather)
get_weather_button.grid(row=2, column=0, columnspan=2, padx=5, pady=5)
# Define the labels to display the weather data
temperature_label = tk.Label(root, text="")
temperature_label.grid(row=3, column=0, columnspan=2, padx=5, pady=5)
weather_desc_label = tk.Label(root, text="")
weather_desc_label.grid(row=4, column=0, columnspan=2, padx=5, pady=5)
# Run the GUI window
root.mainloop()
在这个例子中,我们首先导入必要的库:tkinter和requests。然后设置我们的weatherstack API密钥并定义API URL。我们使用 tk.Tk() 函数创建一个GUI窗口,并设置窗口标题。
我们使用 tk.Label() 和 tk.Entry() 函数创建两个标签和两个输入字段,用于城市和国家。然后我们定义一个名为 get_weather() 的函数,该函数从API获取天气数据并在GUI中显示。该函数使用 requests.get() 函数对API URL进行GET请求,并使用输入字段中的城市和国家。然后从JSON响应中提取温度和天气描述数据,并更新GUI中的温度和天气描述标签。
我们使用 tk.Button() 函数创建一个按钮来获取天气数据,其中 command 参数设置为 get_weather() 函数。我们还创建两个标签来显示温度和天气描述数据。
最后,我们使用 root.mainloop() 函数运行GUI窗口。当用户输入城市和国家并点击“获取天气”按钮时, get_weather() 函数将向API发起请求。
输出
这张图片展示了我们输入城市和国家名称后,天气应用程序GUI的输出。API密钥将根据用户的不同而变化。
结论
在本教程中,我们学习了如何在Python中使用weatherstack API创建天气预报的GUI。我们已经介绍了构建GUI和从weatherstack API检索数据的必要步骤。我们还解释了每个子部分并提供了使用weatherstack API的天气预报应用程序的实际示例。