以前礼饱,公眾號分享了如何使用 PyQt5 制作猜數(shù)游戲和計時器,這一次日裙,我們繼續(xù)學習:如何使用 PyQt5 制作天氣查詢軟件溺健。
如需獲取源代碼和 exe 文件麦牺,請在微信公眾號Python高效編程
后臺回復: 天氣
。
開發(fā)環(huán)境
- Python3
- PyQt5
- requests
準備工作
首先要獲取不同城市對應的天氣代碼鞭缭,可以從https://www.heweather.com/documents/city.html 網站下載 csv 文件(文末獲取 csv 文件)剖膳,拿到 csv 文件,我們首先要進行數(shù)據(jù)預處理工作岭辣。
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)
# 建立城市與代碼之間的映射關系
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ù)存儲為 txt 文件
import json
filename = 'city_code.txt'
with open(filename, 'w') as f:
json.dump(code_dict, f)
將字典存儲為 txt 文件后,以后我們只需讀取文件沦童,再獲取字典:
with open(filename, 'r') as f:
text = json.load(f)
如果不想費工夫處理這些數(shù)據(jù)仑濒,可以直接使用文末提供的 city_code.txt 文件。
Ui 設計
使用 Qt Designer偷遗,我們不難設計出以下界面:
如果不想設計這些界面墩瞳,可以直接導入我提供的 Ui_weather.py 文件。
主體邏輯:
我們這次使用的 api 接口為:'http://wthrcdn.etouch.cn/weather_mini?citykey={code}'氏豌,code 就是之前處理過的城市代碼喉酌,比如常州的城市代碼為:101191101。替換掉變量 code ,網站返回給我們一段 json 格式的文件:
根據(jù)這段 json 語句泪电,我們很容易提取需要的信息:
# 天氣情況
data = info_json['data']
city = f"城市:{data['city']}\n"
today = data['forecast'][0]
date = f"日期:{today['date']}\n"
now = f"實時溫度:{data['wendu']}度\n"
temperature = f"溫度:{today['high']} {today['low']}\n"
fengxiang = f"風向:{today['fengxiang']}\n"
type = f"天氣:{today['type']}\n"
tips = f"貼士:{data['ganmao']}\n"
當然般妙,我們首先要使用 requests,get 方法,來獲取這段 json 代碼相速。
def query_weather(code):
# 模板網頁
html = f'http://wthrcdn.etouch.cn/weather_mini?citykey={code}'
# 向網頁發(fā)起請求
try:
info = requests.get(html)
info.encoding = 'utf-8'
# 捕獲 ConnectinError 異常
except requests.ConnectionError:
raise
# 將獲取的數(shù)據(jù)轉換為 json 格式
try:
info_json = info.json()
# 轉換失敗提示無法查詢
except JSONDecodeError:
return '無法查詢'
下面我們介紹下本文用到的控件方法:
# 將 textEdit 設置為只讀模式
self.textEdit.setReadOnly(True)
# 將鼠標焦點放在 lineEdit 編輯欄里
self.lineEdit.setFocus()
# 獲取 lineEdit 中的文本
city = self.lineEdit.text()
# 設置文本
self.textEdit.setText(info)
# 清空文本
self.lineEdit.clear()
為查詢按鈕設置快捷鍵:
def keyPressEvent(self, e):
# 設置快捷鍵
if e.key() == Qt.Key_Return:
self.queryWeather()
最后碟渺,我們可以使用 Pyinstaller -w weather.py 打包應用程序,但是要記得打包完突诬,將 city_code.txt 復制到 dist/weather 文件夾下止状,否則程序無法運行。
以上便是本文的全部內容了攒霹,更詳細的內容請見源代碼。如需獲取源代碼和 exe 文件浆洗,請在微信公眾號Python高效編程
后臺回復: 天氣
催束。