
以前,公眾號(hào)分享了如何使用 PyQt5 制作猜數(shù)游戲和計(jì)時(shí)器,這一次,我們繼續(xù)學(xué)習(xí):如何使用 PyQt5 制作天氣查詢軟件。
如需獲取源代碼和 exe 文件,請(qǐng)?jiān)谖⑿殴娞?hào)Python高效編程后臺(tái)回復(fù): 天氣。
開發(fā)環(huán)境
- Python3
- PyQt5
- requests
準(zhǔn)備工作
首先要獲取不同城市對(duì)應(yīng)的天氣代碼,可以從https://www.heweather.com/documents/city.html 網(wǎng)站下載 csv 文件(文末獲取 csv 文件),拿到 csv 文件,我們首先要進(jìn)行數(shù)據(jù)預(yù)處理工作。
import pandas as pd
# 將下載好的文件命名為 'city_code.csv',并刪除 header
file = pd.read_csv('city_code.csv')
# 選取需要的兩列信息
file = file.loc[:,['City_ID', 'City_CN']]
# 讀取前五行信息
file.head()

# 匹配 City_ID 中的數(shù)字
def convert(x):
pat = re.compile('(\d+)')
return pat.search(x).group()
file['City_ID_map'] = file['City_ID'].map(convert)
# 建立城市與代碼之間的映射關(guān)系
def city2id(file):
code_dict = {}
key = 'City_CN'
value = 'City_ID_map'
for k, v in zip(file[key], file[value]):
code_dict[k] = v
return code_dict
code_dict = city2id(file)
# 將所得的字典數(shù)據(jù)存儲(chǔ)為 txt 文件
import json
filename = 'city_code.txt'
with open(filename, 'w') as f:
json.dump(code_dict, f)
將字典存儲(chǔ)為 txt 文件后,以后我們只需讀取文件,再獲取字典:
with open(filename, 'r') as f:
text = json.load(f)
如果不想費(fèi)工夫處理這些數(shù)據(jù),可以直接使用文末提供的 city_code.txt 文件。
Ui 設(shè)計(jì)
使用 Qt Designer,我們不難設(shè)計(jì)出以下界面:
如果不想設(shè)計(jì)這些界面,可以直接導(dǎo)入我提供的 Ui_weather.py 文件。
主體邏輯:
我們這次使用的 api 接口為:'http://wthrcdn.etouch.cn/weather_mini?citykey={code}',code 就是之前處理過的城市代碼,比如常州的城市代碼為:101191101。替換掉變量 code ,網(wǎng)站返回給我們一段 json 格式的文件:
根據(jù)這段 json 語句,我們很容易提取需要的信息:
# 天氣情況
data = info_json['data']
city = f"城市:{data['city']}\n"
today = data['forecast'][0]
date = f"日期:{today['date']}\n"
now = f"實(shí)時(shí)溫度:{data['wendu']}度\n"
temperature = f"溫度:{today['high']} {today['low']}\n"
fengxiang = f"風(fēng)向:{today['fengxiang']}\n"
type = f"天氣:{today['type']}\n"
tips = f"貼士:{data['ganmao']}\n"
當(dāng)然,我們首先要使用 requests,get 方法,來獲取這段 json 代碼。
def query_weather(code):
# 模板網(wǎng)頁
html = f'http://wthrcdn.etouch.cn/weather_mini?citykey={code}'
# 向網(wǎng)頁發(fā)起請(qǐng)求
try:
info = requests.get(html)
info.encoding = 'utf-8'
# 捕獲 ConnectinError 異常
except requests.ConnectionError:
raise
# 將獲取的數(shù)據(jù)轉(zhuǎn)換為 json 格式
try:
info_json = info.json()
# 轉(zhuǎn)換失敗提示無法查詢
except JSONDecodeError:
return '無法查詢'
下面我們介紹下本文用到的控件方法:
# 將 textEdit 設(shè)置為只讀模式
self.textEdit.setReadOnly(True)
# 將鼠標(biāo)焦點(diǎn)放在 lineEdit 編輯欄里
self.lineEdit.setFocus()
# 獲取 lineEdit 中的文本
city = self.lineEdit.text()
# 設(shè)置文本
self.textEdit.setText(info)
# 清空文本
self.lineEdit.clear()
為查詢按鈕設(shè)置快捷鍵:
def keyPressEvent(self, e):
# 設(shè)置快捷鍵
if e.key() == Qt.Key_Return:
self.queryWeather()
最后,我們可以使用 Pyinstaller -w weather.py 打包應(yīng)用程序,但是要記得打包完,將 city_code.txt 復(fù)制到 dist/weather 文件夾下,否則程序無法運(yùn)行。
以上便是本文的全部內(nèi)容了,更詳細(xì)的內(nèi)容請(qǐng)見源代碼。如需獲取源代碼和 exe 文件,請(qǐng)?jiān)谖⑿殴娞?hào)Python高效編程后臺(tái)回復(fù): 天氣。