吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 7635|回复: 29
收起左侧

[Python 转载] PyQt5+Python3.7写一个快速天气查询工具

[复制链接]
huhus123 发表于 2018-12-26 13:38
本帖最后由 huhus123 于 2019-1-15 10:42 编辑

感觉PyQt5的学习资源比较少,只能摸着石头过河,简单写个小工具练练手。


窗体文件如下


[Python] 纯文本查看 复制代码
# -*- coding: utf-8 -*-

# Date:2018-12-12
#
# Created by: DaddyHu_CN
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.setWindowModality(QtCore.Qt.NonModal)
        Form.setEnabled(True)
        Form.resize(436, 336)
        Form.setMinimumSize(QtCore.QSize(436, 336))
        Form.setMaximumSize(QtCore.QSize(436, 336))
        self.groupBox = QtWidgets.QGroupBox(Form)
        self.groupBox.setGeometry(QtCore.QRect(10, 10, 421, 250))
        self.groupBox.setObjectName("groupBox")
        self.formLayout = QtWidgets.QFormLayout(self.groupBox)
        self.formLayout.setObjectName("formLayout")
        self.label = QtWidgets.QLabel(self.groupBox)
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(11)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label)
        self.weatherComboBox = QtWidgets.QComboBox(self.groupBox)
        self.weatherComboBox.setObjectName("weatherComboBox")
        self.weatherComboBox.addItem("")
        self.weatherComboBox.addItem("")
        self.weatherComboBox.addItem("")
        self.weatherComboBox.addItem("")
        self.weatherComboBox.addItem("")
        self.weatherComboBox.addItem("")
        self.weatherComboBox.addItem("")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.weatherComboBox)
        self.resultText = QtWidgets.QTextEdit(self.groupBox)
        self.resultText.setEnabled(True)
        self.resultText.setReadOnly(True)
        self.resultText.setObjectName("resultText")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.SpanningRole, self.resultText)
        self.queryBtn = QtWidgets.QPushButton(Form)
        self.queryBtn.setGeometry(QtCore.QRect(70, 280, 101, 31))
        self.queryBtn.setObjectName("queryBtn")
        self.clearBtn = QtWidgets.QPushButton(Form)
        self.clearBtn.setEnabled(True)
        self.clearBtn.setGeometry(QtCore.QRect(260, 280, 101, 31))
        self.clearBtn.setObjectName("clearBtn")
        self.queryBtn.raise_()
        self.groupBox.raise_()
        self.clearBtn.raise_()

        self.retranslateUi(Form)
        self.queryBtn.clicked.connect(Form.queryWeather)
        self.clearBtn.clicked.connect(Form.clearResult)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "天气快速查询"))
        self.groupBox.setTitle(_translate("Form", "查询城市天气"))
        self.label.setText(_translate("Form", "  城市"))
        self.weatherComboBox.setItemText(0, _translate("Form", "北京"))
        self.weatherComboBox.setItemText(1, _translate("Form", "上海"))
        self.weatherComboBox.setItemText(2, _translate("Form", "天津"))
        self.weatherComboBox.setItemText(3, _translate("Form", "重庆"))
        self.weatherComboBox.setItemText(4, _translate("Form", "郑州"))
        self.weatherComboBox.setItemText(5, _translate("Form", "长沙"))
        self.weatherComboBox.setItemText(6, _translate("Form", "乌鲁木齐"))
        self.queryBtn.setText(_translate("Form", "查询"))
        self.clearBtn.setText(_translate("Form", "清空"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())



核心代码如下
[Python] 纯文本查看 复制代码
from PyQt5.QtWidgets import QApplication,  QMainWindow
from WeatherWin import Ui_Form
import sys
from PyQt5.QtCore import *
import requests
import time
from bs4 import BeautifulSoup

class MainWindow(QMainWindow):
    def __init__(self,  parent=None):
        super(MainWindow,  self).__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
    
    def queryWeather(self):
        global cityCode
        cityName = self.ui.weatherComboBox.currentText()
        cityCode = self.transCityName(cityName)
        self.thread = WorkThread()
        self.thread.trigger.connect(self.writeText)
        self.thread.start()
    
    def writeText(self,  text):
        self.ui.resultText.setText(text)
        
        
    def transCityName(self,  cityName):
        cityCode = ''
        if cityName == '北京':
            cityCode = '101010100'
        elif cityName == '上海':
            cityCode = '101020100'
        elif cityName == '天津':
            cityCode = '101030100'
        elif cityName == '长沙':
            cityCode = '101250101'
        elif cityName == '乌鲁木齐':
            cityCode = '101130101'
        elif cityName == '重庆':
            cityCode = '101040100'
        elif cityName == '郑州':
            cityCode = '101180101'
        return cityCode
    
    def clearResult(self):
        self.ui.resultText.clear()

class WorkThread(QThread):
    trigger = pyqtSignal(str)
    def __init__(self):
        super(WorkThread,  self).__init__()
        
        
    def run(self):
        global cityCode
        times = str(time.time()).split('.')
        times = ''.join(times[0]+times[1][0:3])
        headers = { 
                          "Connection":'keep-alive',
                          'Host':'d1.weather.com.cn',
                          'Referer':'http://www.weather.com.cn/weather1d/%s.shtml' % cityCode,
                          'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
                        }
        url = 'http://d1.weather.com.cn/sk_2d/%s.html?_=%s' % (cityCode, times)
        rep = requests.get(url,  headers=headers)
        rep = rep.content
        page = BeautifulSoup(rep, 'lxml')
        page = page.text.split('=')
        page = eval(page[1])
        oxgan = ['优',  '良',  '轻度污染',  '中度污染',  '重度污染',  '极度污染']
        live = int(page['aqi'])
        if 0<=live<=50:
            oxgan = oxgan[0]
        elif 50<live<=100:
            oxgan = oxgan[1]
        elif 100<live<=150:
            oxgan = oxgan[2]
        elif 150<live<=200:
            oxgan = oxgan[3]
        elif 200<live<=300:
            oxgan = oxgan[3]
        elif 300<live<=500:
            oxgan = oxgan[3]
        msg1 = '城市: %s\n' % page['cityname']
        msg2 = '温度: %s' % page['temp'] + '℃\n'
        msg3 = '风向: %s\n' % page['WD']
        msg4 = '风力: %s\n' % page['WS']
        msg5 = '湿度: %s\n' % page['SD']
        msg6 = '空气质量: %s ' % page['aqi'] + oxgan + '\n'
        msg7 = '时间: %s %s\n' % (page['date'], page['time'])
        msg8 = '\n\n\n\n\t by:DaddyHu_CN'
        result = msg1 + msg2 + msg3 + msg4 + msg5 + msg6 + msg7 + msg8
        self.trigger.emit(result)

        

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
sys.exit(app.exec_())


涉及简单的爬虫和抓包的知识,都是很简单很简单的,仅供学习探讨。

企业微信截图_15458028296468.png

运行效果如图


上下分别保存成.py文件运行下面那个即可,需要pyqt5支持,具体需要什么模块请自行安装吧,希望大家都有点动探索精神,都是要学习的别等着别人喂给你,谢谢!

免费评分

参与人数 4吾爱币 +2 热心值 +4 收起 理由
hohov + 1 谢谢@Thanks!
奥斯特 + 1 + 1 谢谢@Thanks!
爱破解的我 + 1 + 1 我很赞同!
zzzain46 + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

hiberoo 发表于 2019-1-4 23:39
楼主你试了吗,你的代码是跑不起来的,返回天气数据并不是webservice格式,只是简单的json字节码而已。
page = BeautifulSoup(rep, 'lxml')
        page = page.text.split('=')
        page = eval(page[1])
这样解不出来的
应换成
rep = rep.content.decode('utf-8')
                json_str = rep.split('=')[1]
                page = json.loads(json_str)
才行
 楼主| huhus123 发表于 2018-12-30 19:14
787821 发表于 2018-12-27 22:23
你说的对,这么简单的GUI用pyqt浪费太多内存了

几千行的也有不想贴,您觉得能浪费多少内存?
Bean.Wei 发表于 2018-12-26 21:27
 楼主| huhus123 发表于 2018-12-27 16:14
Bean.Wei 发表于 2018-12-26 21:27
界面过于简单了些,不如直接用Tk。

只是为了学习qt做铺垫
Bean.Wei 发表于 2018-12-27 19:01
那还有好长的路走 哈哈
787821 发表于 2018-12-27 22:23
Bean.Wei 发表于 2018-12-26 21:27
界面过于简单了些,不如直接用Tk。

你说的对,这么简单的GUI用pyqt浪费太多内存了
 楼主| huhus123 发表于 2018-12-30 19:15
Bean.Wei 发表于 2018-12-27 19:01
那还有好长的路走 哈哈

您可以贴一个您的开发项目,让我学习学习
hp140715 发表于 2018-12-31 08:06 来自手机
呵呵谢谢楼主分享
sunzhiqiang 发表于 2018-12-31 15:27
总之还是可以的哈哈
 楼主| huhus123 发表于 2019-1-1 03:28
sunzhiqiang 发表于 2018-12-31 15:27
总之还是可以的哈哈

简单的没人看,难得又没几个看得懂,现在人学习眼高手低,唉
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-16 23:33

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表