用 Python 編寫一個天氣查詢應用 pyqt5

 

效果預覽:css

html


 

 

1、獲取天氣信息python

 

使用python獲取天氣有兩種方式。json

 

1)是經過爬蟲的方式獲取天氣預報網站的HTML頁面,而後使用xpath或者bs4解析HTML界面的內容。瀏覽器

 

2)另外一種方式是根據天氣預報網站提供的API,直接獲取結構化數據,省去了解析HTML頁面的步驟。app

 

本例使用的是第二種方式,請求地址爲:函數

http://wthrcdn.etouch.cn/weather_mini?citykey=城市代碼網站

 

部分城市代碼對應:ui

北京 101010100url

天津 101030100

上海 101020100

瀏覽器返回的天津氣溫狀況以下,該信息其實就是一個JSON字符串,格式化以後的樣子以下所示:

 

 

{
    "data": {
        "yesterday": {
            "date": "1日星期五",
            "high": "高溫 17℃",
            "fx": "東北風",
            "low": "低溫 8℃",
            "fl": "<![CDATA[<3級]]>",
            "type": "多雲"
        },
        "city": "北京",
        "forecast": [
            {
                "date": "2日星期六",
                "high": "高溫 14℃",
                "fengli": "<![CDATA[<3級]]>",
                "low": "低溫 8℃",
                "fengxiang": "北風",
                "type": "小雨"
            },

        ],
        "ganmao": "晝夜溫差較大,較易發生感冒,請適當增減衣服。體質較弱的朋友請注意防禦。",
        "wendu": "12"
    },
    "status": 1000,
    "desc": "OK"
}

 

獲取天氣的主要代碼以下:

 

 

# cityCode 替換爲具體某一個城市的對應編號

# 一、發送請求,獲取數據
url = f'http://wthrcdn.etouch.cn/weather_mini?citykey={cityCode}'
res = requests.get(url)
res.encoding = 'utf-8'

res_json = res.json()

# 二、數據格式化
data = res_json['data']
city = f"城市:{data['city']}
"  
# 字符串格式化的一種方式 f"{}" 經過字典傳遞值

today = data['forecast'][0]
date = f"日期:{today['date']}
"  # 
 換行
now = f"實時溫度:{data['wendu']}度
"
temperature = f"溫度:{today['high']} {today['low']}
"
fengxiang = f"風向:{today['fengxiang']}
"
type = f"天氣:{today['type']}
"
tips = f"貼士:{data['ganmao']}
"

result = city + date + now + temperature + fengxiang + type + tips

print(result)

 

2、界面的實現

 

一、使用Qt Designer繪製窗口,保存爲ui文件

 

 

二、把ui文件轉爲py文件

 

1)在生成的ui文件目錄下,打開cmd

2)輸入如下命令(注意替換名稱)

 

 

pyuic5 -o destination.py source.ui

 

三、信號與槽函數的鏈接

 

 

# 一、清空按鈕與對應函數鏈接
clearBtn.clicked.connect(widget.clearResult)

# 二、查詢按鈕與對應函數鏈接
queryBtn.clicked.connect(widget.queryWeather)

 

四、調用主窗口類

 

 

import sys     
from PyQt5.QtWidgets import QApplication , QMainWindow
from WeatherWin import Ui_widget
import requests
import json

class MainWindow(QMainWindow ):
    def __init__(self, parent=None):    
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_widget()
        self.ui.setupUi(self)

        # 經過文本框傳入想要搜索的城市名稱:天津
        cityName = self.ui.weatherComboBox.currentText()

        # 獲取天氣部分省略

        # 在文本框顯示查詢結果
        self.ui.resultText.setText(result)

    def clearResult(self):
        print('* clearResult  ')
        self.ui.resultText.clear()  

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

 

以上,提供了獲取天氣(GUI)程序的主要過程及部分源碼。

一、獲取天氣信息

二、繪製可視化界面

三、把ui文件轉成py文件

四、信號與槽

五、調用主窗口類


效果預覽:

 

 

1、獲取天氣信息

 

使用python獲取天氣有兩種方式。

 

1)是經過爬蟲的方式獲取天氣預報網站的HTML頁面,而後使用xpath或者bs4解析HTML界面的內容。

 

2)另外一種方式是根據天氣預報網站提供的API,直接獲取結構化數據,省去了解析HTML頁面的步驟。

 

本例使用的是第二種方式,請求地址爲:http://wthrcdn.etouch.cn/weather_mini?citykey=城市代碼

 

部分城市代碼對應:

北京 101010100

天津 101030100

上海 101020100

瀏覽器返回的天津氣溫狀況以下,該信息其實就是一個JSON字符串,格式化以後的樣子以下所示:

 

{
    "data": {
        "yesterday": {
            "date""1日星期五",
            "high""高溫 17℃",
            "fx""東北風",
            "low""低溫 8℃",
            "fl""<![CDATA[<3級]]>",
            "type""多雲"
        },
        "city""北京",
        "forecast": [
            {
                "date""2日星期六",
                "high""高溫 14℃",
                "fengli""<![CDATA[<3級]]>",
                "low""低溫 8℃",
                "fengxiang""北風",
                "type""小雨"
            },

        ],
        "ganmao""晝夜溫差較大,較易發生感冒,請適當增減衣服。體質較弱的朋友請注意防禦。",
        "wendu""12"
    },
    "status"1000,
    "desc""OK"
}

 

獲取天氣的主要代碼以下:

 

# cityCode 替換爲具體某一個城市的對應編號# 一、發送請求,獲取數據
url = f'http://wthrcdn.etouch.cn/weather_mini?citykey={cityCode}'
res = requests.get(url)
res.encoding = 
'utf-8'res_json = res.json()

# 二、數據格式化
data = res_json[
'data']
city = 
f"城市:{data['city']}
"
  
# 字符串格式化的一種方式 f"{}" 經過字典傳遞值

today = data[
'forecast'][0]
date = 
f"日期:{today['date']}
"
  
 換行

now = 
f"實時溫度:{data['wendu']}
"

temperature = 
f"溫度:{today['high']} {today['low']}
"

fengxiang = 
f"風向:{today['fengxiang']}
"

type = 
f"天氣:{today['type']}
"

tips = 
f"貼士:{data['ganmao']}
"


result = city + date + now + temperature + fengxiang + type + tips

print(result)
 

2、界面的實現

 

一、使用Qt Designer繪製窗口,保存爲ui文件

 

 

二、把ui文件轉爲py文件

 

1)在生成的ui文件目錄下,打開cmd2)輸入如下命令(注意替換名稱)

 

pyuic5 -o destination.py source.ui

 

三、信號與槽函數的鏈接

 

# 一、清空按鈕與對應函數鏈接
clearBtn.clicked.connect(widget.clearResult)

# 二、查詢按鈕與對應函數鏈接
queryBtn.clicked.connect(widget.queryWeather)

 

四、調用主窗口類

 

import sys     
from PyQt5.QtWidgets import QApplication , QMainWindow
from WeatherWin import Ui_widget
import requests
import json

class MainWindow(QMainWindow ):
    def __init__(self, parent=None):    
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_widget()
        self.ui.setupUi(self)

        # 經過文本框傳入想要搜索的城市名稱:天津
        cityName = self.ui.weatherComboBox.currentText()

        # 獲取天氣部分省略

        # 在文本框顯示查詢結果
        self.ui.resultText.setText(result)

    def clearResult(self):
        print('* clearResult  ')
        self.ui.resultText.clear()  

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

 

以上,提供了獲取天氣(GUI)程序的主要過程及部分源碼。

一、獲取天氣信息

二、繪製可視化界面

三、把ui文件轉成py文件

四、信號與槽

五、調用主窗口類

相關文章
相關標籤/搜索