Python实现天气查询工具:PyQt5与Tkinter双方案详解
本文详细介绍如何使用Python开发天气查询应用,提供PyQt5与Tkinter两种图形界面实现方案。内容涵盖从Qt Designer绘制UI到生成Python代码的完整流程,重点解析信号与槽函数的连接机制,以及通过requests库调用天气API并解析JSON数据的核心逻辑。
Python天气查询工具开发概述
实现天气查询功能的核心代码逻辑如下:
PyQt5方案:UI设计与API数据获取
# cityCode 替换为具体某一个城市的对应编号
# 1、发送请求,获取数据
url = f'http://wthrcdn.etouch.cn/weather_mini?citykey={cityCode}'
res = requests.get(url)
res.encoding = 'utf-8'
res_json = res.json()
# 2、数据格式化
data = res_json['data']
city = f"城市:{data['city']}\n"
# 字符串格式化的一种方式 f"{}" 通过字典传递值
today = data['forecast'][0]
date = f"日期:{today['date']}\n" # \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"
result = city + date + now + temperature + fengxiang + type + tips
print(result)
第一步,利用Qt Designer工具设计用户界面,并将设计好的布局保存为.ui格式文件。
第二步,将生成的.ui文件转换为可直接在Python中调用的.py文件。
具体操作如下:
在包含.ui文件的目录下打开命令行终端(cmd),并执行转换命令。请注意替换命令中的实际文件名。
pyuic5 -o destination.py source.ui
第三步,建立界面控件与后端处理函数之间的信号与槽连接,确保用户交互能触发相应逻辑。
信号与槽机制连接
# 1、清空按钮与对应函数连接
clearBtn.clicked.connect(widget.clearResult)
# 2、查询按钮与对应函数连接
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_())
代码补充说明:
Tkinter方案:基础界面与数据解析
from tkinter import *
import urllib.request
import gzip
import json
from tkinter import messagebox
root = Tk()
def main():
# 输入窗口
root.title('Python学习交流群:973783996') # 窗口标题
Label(root, text='请输入城市').grid(row=0, column=0) # 设置标签并调整位置
enter = Entry(root) # 输入框
enter.grid(row=0, column=1, padx=20, pady=20) # 调整位置
enter.delete(0, END) # 清空输入框
enter.insert(0, 'Python学习交流群:973783996') # 设置默认文本
# enter_text = enter.get()#获取输入框的内容
running = 1
def get_weather_data(): # 获取网站数据
city_name = enter.get() # 获取输入框的内容
url1 = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(city_name)
url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
# 网址1只需要输入城市名,网址2需要输入城市代码
# print(url1)
weather_data = urllib.request.urlopen(url1).read()
# 读取网页数据
weather_data = gzip.decompress(weather_data).decode('utf-8')
# 解压网页数据
weather_dict = json.loads(weather_data)
# 将json数据转换为dict数据
if weather_dict.get('desc') == 'invilad-citykey':
print(messagebox.askokcancel("xing", "你输入的城市名有误,或者天气中心未收录你所在城市"))
else:
# print(messagebox.askokcancel('xing','bingguo'))
show_data(weather_dict, city_name) def show_data(weather_dict, city_name): # 显示数据
forecast = weather_dict.get('data').get('forecast') # 获取数据块
root1 = Tk() # 副窗口
root1.geometry('650x280') # 修改窗口大小
root1.title(city_name + '天气状况') # 副窗口标题
# 设置日期列表
for i in range(5): # 将每一天的数据放入列表中
LANGS = [(forecast[i].get('date'), '日期'),
(forecast[i].get('fengxiang'), '风向'),
(str(forecast[i].get('fengji')), '风级'),
(forecast[i].get('high'), '最高温'),
(forecast[i].get('low'), '最低温'),
(forecast[i].get('type'), '天气')]
group = LabelFrame(root1, text='天气状况', padx=0, pady=0) # 框架
group.pack(padx=11, pady=0, side=LEFT) # 放置框架
for lang, value in LANGS: # 将数据放入框架中
c = Label(group, text=value + ': ' + lang)
c.pack(anchor=W)
Label(root1, text='今日' + weather_dict.get('data').get('ganmao'),
fg='green').place(x=40, y=20, height=40) # 温馨提示
Label(root1, text="StarMan: 49star.com", fg="green", bg="yellow").place(x=10, y=255, width=125, height=20) # 作者网站
Button(root1, text='确认并退出', width=10, command=root1.quit).place(x=500, y=230, width=80, height=40) # 退出按钮
root1.mainloop()
# 布置按键
Button(root, text="确认", width=10, command=get_weather_data) \
.grid(row=3, column=0, sticky=W, padx=10, pady=5)
Button(root, text='退出', width=10, command=root.quit) \
.grid(row=3, column=1, sticky=E, padx=10, pady=5)
if running == 1:
root.mainloop()
if __name__ == '__main__':
main()
至此,关于使用Python脚本制作天气查询工具的实例介绍完毕。如需了解更多Python天气查询相关内容,建议查阅本站历史文章或继续浏览后续教程,期待大家的支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













