作者 | 俊欣
来源 | 关于数据分析于可视化(ID:dylanxia2019)
根据"中国天气"微博消息,今年下半年以来最强冷空气已经启程,未来的日子里将横扫我国中东部大部分地区,给多地都带来"断崖式"地降温,局部地区的降温幅度达到了12℃,小编穿着短袖、短裤地走在路上也是感到了阵阵地寒意。
今天小编来利用Python和PyQt5来一键生成未来五天内所在当地的天气预报,以便我们更好的来抵御寒冷,预防感冒。
效果显示
制作过程
首先引入需要用到的库:
import sys
import requests
import json
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QPushButton, QLineEdit, QLabel
from PyQt5.QtGui import QIcon
后端代码逻辑部分
我们先来处理后端的部分,通过requests库来抓取当地的天气情况,并且数据格式是以json格式返回
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'}city_name = "上海"weather_url = 'http://wthrcdn.etouch.cn/weather_mini?city={}'.format(city_name)city_response = requests.get(weather_url, headers=headers)weather_dict = json.loads(city_response.text)forecast_weather = weather_dict.get('data').get('forecast')
然后加入我们需要未来5天的天气情况,直接写一个for循环即可,如下
weather_report = []
for i in range(5):
weather_report.append('日期:' + forecast_weather[i].get('date') + '\n'
+ '天气状况:' + forecast_weather[i].get('type') + '\n'
+ '最高温度:' + forecast_weather[i].get('high') + '\n'
+ '最低温度:' + forecast_weather[i].get('low') + '\n'
+ '风向:' + forecast_weather[i].get('fengxiang') + '\n')
前端页面的设计
前端页面的设计我们用的是PyQt5,在这里不做详细的介绍,小编会在后续中对PyQt5的使用再做专门的讲解,代码如下:
class GetWeather(QWidget): def __init__(self): super().__init__() self.lb = QLabel(self) self.lb.setGeometry(70, 25, 80, 40) self.lb.setText('请输入城市:') self.textbox = QLineEdit(self) self.textbox.setGeometry(170, 30, 130, 30) self.findButton = QPushButton('查询', self) self.findButton.setGeometry(60, 85, 100, 40) self.quitButton = QPushButton('退出', self) self.quitButton.clicked.connect(self.close) self.findButton.clicked.connect(self.find_weather) self.quitButton.setGeometry(190, 85, 100, 40) self.setGeometry(500, 500, 350, 150) self.setWindowTitle('Icon') self.setWindowTitle('天气查询,目前仅支持单次查询') self.setWindowIcon(QIcon('751.png')) self.show()
页面显示的模样如下图:
打包成可执行文件(exe)
最后我们用pyinstaller将整个脚本整合成一个可执行文件,鼠标的双击便可打开使用:
pyinstaller main.py --onefile --name MyExecutable --windowed
最后出来的结果如下:
出来的效果如下图所示: