用python实现天气界面
时间: 2024-06-09 07:04:46 浏览: 76
要实现一个天气界面,可以利用Python中的GUI库,例如Tkinter,来创建一个简单的图形用户界面。以下是一个示例代码:
import tkinter as tk
import requests
def get_weather(city):
# 使用API获取天气信息
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_API_KEY&units=metric'
response = requests.get(url)
data = response.json()
# 解析天气信息并返回
weather = {
'description': data['weather'][0]['description'],
'temperature': data['main']['temp'],
'humidity': data['main']['humidity']
}
return weather
def show_weather():
# 获取输入框中的城市名并获取天气信息
city = city_entry.get()
weather = get_weather(city)
# 更新天气信息标签
description_label.config(text=weather['description'])
temperature_label.config(text=f"{weather['temperature']}°C")
humidity_label.config(text=f"{weather['humidity']}%")
# 创建主窗口
root = tk.Tk()
root.title("天气查询")
# 创建输入框和查询按钮
city_label = tk.Label(root, text="城市名:")
city_label.grid(row=0, column=0)
city_entry = tk.Entry(root)
city_entry.grid(row=0, column=1)
search_button = tk.Button(root, text="查询", command=show_weather)
search_button.grid(row=0, column=2)
# 创建天气信息标签
description_label = tk.Label(root, text="")
description_label.grid(row=1, column=0, columnspan=3)
temperature_label = tk.Label(root, text="")
temperature_label.grid(row=2, column=0, columnspan=3)
humidity_label = tk.Label(root, text="")
humidity_label.grid(row=3, column=0, columnspan=3)
root.mainloop()
在这个示例中,我们使用了OpenWeatherMap的API来获取天气信息。你需要将YOUR_API_KEY
替换为你自己的API密钥。运行这个脚本后,你将会看到一个简单的天气查询界面,你可以输入城市名并点击“查询”按钮来获取该城市的天气信息。
阅读全文
相关推荐
















