這篇文章主要講解了“Python PyQt5怎么實現城市天氣實時查詢工具”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Python PyQt5怎么實現城市天氣實時查詢工具”吧!

以前,公眾號分享了如何使用 PyQt5 制作猜數游戲和計算器,這一次,我們繼續學習:如何使用 PyQt5 制作天氣查詢軟件。
Python3
PyQt5
requests
首先要獲取不同城市對應的天氣代碼,可以從 https://www.heweather.com/documents/city.html 網站下載 csv 文件(文末獲取 csv 文件),拿到 csv 文件,我們首先要進行數據預處理工作。
import pandas as pd
# 將下載好的文件命名為 'city_code.csv'
file = pd.read_csv('city_code.csv')
# 選取需要的兩列信息
file = file.loc[:,['City_ID', 'City_CN']]
# 讀取前五行信息
file.head()
# 匹配 City_ID 中的數字
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_dictcode_dict = city2id(file)
# 將所得的字典數據存儲為 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)
如果不想費工夫處理這些數據,可以直接使用文末提供的 city_code.txt 文件。
使用 Qt Designer,我們不難設計出以下界面:

根據這段 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}' # 向網頁發起請求 try: info = requests.get(html) info.encoding = 'utf-8' # 捕獲 ConnectinError 異常 except requests.ConnectionError: raise # 將獲取的數據轉換為 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 文件夾下,否則程序無法運行。
感謝各位的閱讀,以上就是“Python PyQt5怎么實現城市天氣實時查詢工具”的內容了,經過本文的學習后,相信大家對Python PyQt5怎么實現城市天氣實時查詢工具這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。