窗口tkinter天气
时间: 2023-09-19 13:06:28 浏览: 45
好的,您需要一个 Python 程序,可以使用 tkinter GUI 库创建一个窗口,并从天气 API 中获取天气数据。以下是一个简单的示例程序,您可以根据自己的需要进行修改:
```python
import tkinter as tk
import requests
# 天气 API 地址
WEATHER_API_URL = "https://api.openweathermap.org/data/2.5/weather"
# 天气 API 密钥
API_KEY = "YOUR_API_KEY_HERE"
class WeatherApp:
def __init__(self, master):
# 创建 GUI 窗口
self.master = master
master.title("天气预报")
# 创建输入框和按钮
self.city_label = tk.Label(master, text="输入城市:")
self.city_label.pack()
self.city_entry = tk.Entry(master)
self.city_entry.pack()
self.get_weather_button = tk.Button(master, text="获取天气", command=self.get_weather)
self.get_weather_button.pack()
# 创建显示天气信息的标签
self.weather_label = tk.Label(master, text="")
self.weather_label.pack()
def get_weather(self):
# 获取城市名称
city_name = self.city_entry.get()
# 发送 API 请求
params = {"q": city_name, "appid": API_KEY, "units": "metric"}
response = requests.get(WEATHER_API_URL, params=params)
# 解析 API 响应
if response.status_code == 200:
weather_data = response.json()
city = weather_data["name"]
temp = weather_data["main"]["temp"]
desc = weather_data["weather"][0]["description"]
weather_str = f"{city}: {temp:.1f}℃, {desc}"
self.weather_label.config(text=weather_str)
else:
self.weather_label.config(text="获取天气失败")
# 启动 GUI 窗口
root = tk.Tk()
app = WeatherApp(root)
root.mainloop()
```
注意,您需要将 `YOUR_API_KEY_HERE` 替换为您的 OpenWeatherMap API 密钥。此外,此示例程序使用了 OpenWeatherMap 的天气 API,您需要先注册一个账户,获得 API 密钥,然后才能使用该 API。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)