用api和tkinter做一个查询天气的软件
时间: 2024-06-08 19:10:59 浏览: 16
好的,首先你需要注册一个气象数据提供商的API账号。这里我们以和风天气为例,注册地址:https://dev.heweather.com/
注册完成后,你可以在官网上获取到自己的API Key。然后,我们就可以开始编写代码了。
首先,我们需要导入需要的库:
```python
import requests
import tkinter as tk
from tkinter import messagebox
```
然后,我们定义一个函数,用来调用API并获取天气信息:
```python
def get_weather(city):
url = 'https://free-api.heweather.net/s6/weather/now?location={}&key=你的API Key'.format(city)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if data['HeWeather6'][0]['status'] == 'ok':
weather = data['HeWeather6'][0]['now']
return weather
else:
messagebox.showerror('错误', '城市名输入有误,请重新输入!')
else:
messagebox.showerror('错误', '网络异常,请稍后重试!')
```
在这个函数中,我们首先拼接出API请求的URL,然后使用requests库发送请求,并判断请求是否成功。如果成功,我们可以从返回的JSON数据中提取出当前天气信息,然后返回这个信息。如果请求失败,我们弹出一个提示框,告诉用户出现了什么问题。
接下来,我们可以编写一个GUI界面,让用户输入城市名并查询天气。界面代码如下:
```python
class WeatherApp:
def __init__(self):
self.window = tk.Tk()
self.window.title('天气查询')
self.window.geometry('300x150')
self.label = tk.Label(self.window, text='请输入城市名:')
self.label.pack()
self.entry = tk.Entry(self.window)
self.entry.pack()
self.button = tk.Button(self.window, text='查询', command=self.show_weather)
self.button.pack()
self.result = tk.Label(self.window, text='')
self.result.pack()
self.window.mainloop()
def show_weather(self):
city = self.entry.get()
weather = get_weather(city)
if weather:
self.result.config(text='当前温度为{}摄氏度,天气{}'.format(weather['tmp'], weather['cond_txt']))
```
在这个界面中,我们使用了tkinter库来创建窗口、标签、输入框、按钮和文本框。当用户点击查询按钮时,我们调用get_weather函数查询天气信息,并在文本框中显示查询结果。
最后,我们可以创建一个WeatherApp对象,启动这个应用程序:
```python
app = WeatherApp()
```
现在,你就可以使用这个简单的应用程序来查询天气了。注意,你需要将代码中的“你的API Key”替换成你自己的API Key。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)