一、环境准备
开发环境:Python 3.9.2 pycharm PySide6
申请天气情况 API :https://console.amap.com/dev/key/app
designer 设计
ui 目录下 Weather.ui 转换为 Weather.py
结果显示
二、完整代码
import sys
from PySide6 import QtWidgets
import ui.Weather
from PySide6.QtWidgets import QApplication, QDialog
import requests
class Dialog(QtWidgets.QDialog):
def __init__(self):
super(Dialog, self).__init__()
self.clearBtn = None
self.myDlg = ui.Weather.Ui_Dialog()
self.myDlg.setupUi(self)
def queryWeather(self):
cityName = self.myDlg.comboBox.currentText()
cityCode = self.getCode(cityName)
r = requests.get("https://restapi.amap.com/v3/weather/weatherInfo?key=6778d1f26467c63988b2a037903bbb21&city={}".format(
cityCode))
# r.encoding = 'utf-8'
if r.status_code == 200:
data = r.json()['lives'][0]
weatherMsg = '城市:{}\n天气:{}\n温度:{}\n风向:{}\n风力:{}\n湿度:{}\n发布时间:{}\n'.format(
data['city'],
data['weather'],
data['temperature'],
data['winddirection'],
data['windpower'],
data['humidity'],
data['reporttime'],
)
else:
weatherMsg = '天气查询失败,请稍后再试!'
self.myDlg.textEdit.setText(weatherMsg)
def getCode(self, cityName):
cityDict = {"陕西": "610000",
"北京": "110000",
"苏州": "320500",
"上海": "310000"}
return cityDict.get(cityName, '101010100')
def clearText(self):
self.myDlg.textEdit.clear()
if __name__ == '__main__':
myapp = QApplication(sys.argv)
myDlg = Dialog()
myDlg.show()
myDlg.exec()
三、参考
https://zhuanlan.zhihu.com/p/60815507
链接:https://pan.baidu.com/s/15NOyb8FqPwuJVerRtsgzww
提取码:kwk4
https://zhuanlan.zhihu.com/p/446137829