Python tkinter界面实现历史天气查询的示例代码


Posted in Python onAugust 23, 2020

一、实现效果

1. python代码

import requests
from lxml import etree
import re
import tkinter as tk
from PIL import Image, ImageTk
from xpinyin import Pinyin


def get_image(file_nam, width, height):
  im = Image.open(file_nam).resize((width, height))
  return ImageTk.PhotoImage(im)


def spider():
  headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24',
    "referer": "https://lishi.tianqi.com/chengdu/index.html"
  }
  p = Pinyin()
  place = ''.join(p.get_pinyin(b1.get()).split('-'))      # 获取地区文本框的输入 变为拼音
  # 处理用户输入的时间
  # 规定三种格式都可以 2018/10/1 2018年10月1日 2018-10-1
  date = b2.get()  # 获取时间文本框的输入
  if '/' in date:
    tm_list = date.split('/')
  elif '-' in date:
    tm_list = date.split('-')
  else:
    tm_list = re.findall(r'\d+', date)

  if int(tm_list[1]) < 10:    # 1-9月 前面加 0
    tm_list[1] = f'0{tm_list[1]}'
  # 分析网页规律 构造url
  # 直接访问有该月所有天气信息的页面 提高查询效率
  url = f"https://lishi.tianqi.com/{place}/{''.join(tm_list[:2])}.html"
  resp = requests.get(url, headers=headers)
  html = etree.HTML(resp.text)
  # xpath定位提取该日天气信息
  info = html.xpath(f'//ul[@class="thrui"]/li[{int(tm_list[2])}]/div/text()')
  # 输出信息格式化一下
  info1 = ['日期:', '最高气温:', '最低气温:', '天气:', '风向:']
  datas = [i + j for i, j in zip(info1, info)]
  info = '\n'.join(datas)
  t.insert('insert', '    查询结果如下    \n\n')
  t.insert('insert', info)
  print(info)


win = tk.Tk()
win.title('全国各地历史天气查询系统')
win.geometry('500x500')

# 画布 设置背景图片
canvas = tk.Canvas(win, height=500, width=500)
im_root = get_image('test.jpg', width=500, height=500)
canvas.create_image(250, 250, image=im_root)
canvas.pack()

# 单行文本
L1 = tk.Label(win, bg='yellow', text="地区:", font=("SimHei", 12))
L2 = tk.Label(win, bg='yellow', text="时间:", font=("SimHei", 12))
L1.place(x=85, y=100)
L2.place(x=85, y=150)

# 单行文本框 可采集键盘输入
b1 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b2 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b1.place(x=140, y=100)
b2.place(x=140, y=150)

# 设置查询按钮
a = tk.Button(win, bg='red', text="查询", width=25, height=2, command=spider)
a.place(x=160, y=200)

# 设置多行文本框 宽 高 文本框中字体 选中文字时文字的颜色
t = tk.Text(win, width=30, height=8, font=("SimHei", 18), selectforeground='red') # 显示多行文本
t.place(x=70, y=280)

# 进入消息循环
win.mainloop()

2. 运行效果

运行效果如下:

Python tkinter界面实现历史天气查询的示例代码

二、基本思路

导入用到的库

import requests
from lxml import etree
import re
import tkinter as tk
from PIL import Image, ImageTk
from xpinyin import Pinyin

1. 爬虫部分

目标url:https://lishi.tianqi.com/

该网站提供了全国34个省、市所属的2290个地区的历史天气预报查询,数据来源于城市当天的天气信息,可以查询到历史天气气温,历史风向,历史风力等历史天气状况。

Python tkinter界面实现历史天气查询的示例代码

Python tkinter界面实现历史天气查询的示例代码

分析网页可以发现,某个地区、某个月的所有天气数据的url为:https://lishi.tianqi.com/ + 地区名字的拼音 + ‘/' + 年月.html。
根据用户输入的地区和时间,进行字符串的处理,构造出url,用于request请求有该月所有天气信息的页面,获取响应后Xpath定位提取用户输入的要查询的日期的天气信息,查询结果显示在tkinter界面。

爬虫代码如下:

def spider():
  headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24',
    "referer": "https://lishi.tianqi.com/chengdu/index.html"
  }
  p = Pinyin()
  place = ''.join(p.get_pinyin(b1.get()).split('-'))      # 获取地区文本框的输入 变为拼音
  # 处理用户输入的时间
  # 规定三种格式都可以 2018/10/1 2018年10月1日 2018-10-1
  date = b2.get()  # 获取时间文本框的输入
  if '/' in date:
    tm_list = date.split('/')
  elif '-' in date:
    tm_list = date.split('-')
  else:
    tm_list = re.findall(r'\d+', date)

  if int(tm_list[1]) < 10:    # 1-9月 前面加 0
    tm_list[1] = f'0{tm_list[1]}'
  # 分析网页发现规律  构造url
  # 直接访问有该月所有天气信息的页面 提高查询效率
  url = f"https://lishi.tianqi.com/{place}/{''.join(tm_list[:2])}.html"
  resp = requests.get(url, headers=headers)
  html = etree.HTML(resp.text)
  # xpath定位提取该日天气信息
  info = html.xpath(f'//ul[@class="thrui"]/li[{int(tm_list[2])}]/div/text()')
  # 输出信息格式化一下
  info1 = ['日期:', '最高气温:', '最低气温:', '天气:', '风向:']
  datas = [i + j for i, j in zip(info1, info)]
  info = '\n'.join(datas)
  t.insert('insert', '    查询结果如下    \n\n')
  t.insert('insert', info)
  print(info)

2. tkinter界面

代码如下:

def get_image(file_nam, width, height):
  im = Image.open(file_nam).resize((width, height))
  return ImageTk.PhotoImage(im)


win = tk.Tk()
# 设置窗口title和大小
win.title('全国各地历史天气查询系统')
win.geometry('500x500')

# 画布 设置背景图片
canvas = tk.Canvas(win, height=500, width=500)
im_root = get_image('test.jpg', width=500, height=500)
canvas.create_image(250, 250, image=im_root)
canvas.pack()

# 单行文本
L1 = tk.Label(win, bg='yellow', text="地区:", font=("SimHei", 12))
L2 = tk.Label(win, bg='yellow', text="时间:", font=("SimHei", 12))
L1.place(x=85, y=100)
L2.place(x=85, y=150)

# 单行文本框 可采集键盘输入
b1 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b2 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b1.place(x=140, y=100)
b2.place(x=140, y=150)

# 设置查询按钮 点击 调用爬虫函数实现查询
a = tk.Button(win, bg='red', text="查询", width=25, height=2, command=spider)
a.place(x=160, y=200)

# 设置多行文本框 宽 高 文本框中字体 选中文字时文字的颜色
t = tk.Text(win, width=30, height=8, font=("SimHei", 18), selectforeground='red') # 显示多行文本
t.place(x=70, y=280)

# 进入消息循环
win.mainloop()

tkinter界面效果如下:

Python tkinter界面实现历史天气查询的示例代码

到此这篇关于Python tkinter界面实现历史天气查询的示例代码的文章就介绍到这了,更多相关Python tkinter历史天气查询内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python自动zip压缩目录的方法
Jun 28 Python
一篇文章快速了解Python的GIL
Jan 12 Python
python实现简单遗传算法
Mar 19 Python
python通过zabbix api获取主机
Sep 17 Python
对Python _取log的几种方式小结
Jul 25 Python
利用anaconda作为python的依赖库管理方法
Aug 13 Python
Python 多线程其他属性以及继承Thread类详解
Aug 28 Python
解决python 读取 log日志的编码问题
Dec 24 Python
python 识别登录验证码图片功能的实现代码(完整代码)
Jul 03 Python
python 调用Google翻译接口的方法
Dec 09 Python
python 如何用terminal输入参数
May 25 Python
pd.drop_duplicates删除重复行的方法实现
Jun 16 Python
套娃式文件夹如何通过Python批量处理
Aug 23 #Python
python进度条显示-tqmd模块的实现示例
Aug 23 #Python
基于python tkinter的点名小程序功能的实例代码
Aug 22 #Python
python+selenium 简易地疫情信息自动打卡签到功能的实现代码
Aug 22 #Python
python进度条显示之tqmd模块
Aug 22 #Python
python 常见的排序算法实现汇总
Aug 21 #Python
Python制作数据预测集成工具(值得收藏)
Aug 21 #Python
You might like
php基础教程 php内置函数实例教程
2012/08/21 PHP
javascript new 需不需要继续使用
2009/07/02 Javascript
jquery 简单图片导航插件jquery.imgNav.js
2010/03/17 Javascript
JS实现文字链接感应鼠标淡入淡出改变颜色的方法
2015/02/26 Javascript
js实现文字滚动效果
2016/03/03 Javascript
js中开关变量使用实例
2017/02/24 Javascript
jQuery+ajax实现局部刷新的两种方法
2017/06/08 jQuery
各种选择框jQuery的选中方法(实例讲解)
2017/06/27 jQuery
React-Native中props具体使用详解
2017/09/04 Javascript
JavaScript实现body内任意节点的自定义属性功能示例
2017/09/18 Javascript
详解在vue-cli中使用graphql即vue-apollo的用法
2018/09/08 Javascript
小程序云开发初探(小结)
2018/10/24 Javascript
React组件对子组件children进行加强的方法
2019/06/23 Javascript
小程序两种滚动公告栏的实现方法
2019/09/17 Javascript
js+h5 canvas实现图片验证码
2020/10/11 Javascript
[01:31](回顾)杀出重围,决战TI之巅
2014/07/01 DOTA
python冒泡排序简单实现方法
2015/07/09 Python
用Python实现命令行闹钟脚本实例
2016/09/05 Python
python 设置文件编码格式的实现方法
2017/12/21 Python
Python实现调用另一个路径下py文件中的函数方法总结
2018/06/07 Python
Python中函数的基本定义与调用及内置函数详解
2019/05/13 Python
Pandas库之DataFrame使用的学习笔记
2019/06/21 Python
python 实现目录复制的三种小结
2019/12/04 Python
pycharm 中mark directory as exclude的用法详解
2020/02/14 Python
关于css中margin的值和垂直外边距重叠问题
2020/10/27 HTML / CSS
美国著名的团购网站:Woot
2016/08/02 全球购物
党校学习思想汇报
2014/01/06 职场文书
主管会计岗位责任制
2014/02/10 职场文书
大学生社会实践评语
2014/04/25 职场文书
高中生第一学年自我鉴定2015
2014/09/28 职场文书
高中社区服务活动报告
2015/02/05 职场文书
食品安全责任书范本
2015/05/09 职场文书
诚信教育主题班会
2015/08/13 职场文书
《水上飞机》教学反思
2016/02/20 职场文书
只用20行Python代码实现屏幕录制功能
2021/06/02 Python
唤醒紫霞仙子,携手再游三界!大话手游X《大话西游》电影合作专属剧情任务
2022/04/03 其他游戏