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解析中国天气网的天气数据
Mar 21 Python
基于Python代码编辑器的选用(详解)
Sep 13 Python
Python键盘输入转换为列表的实例
Jun 23 Python
python3 拼接字符串的7种方法
Sep 12 Python
Python/ArcPy遍历指定目录中的MDB文件方法
Oct 27 Python
Python中的异常处理try/except/finally/raise用法分析
Feb 28 Python
详解Python传入参数的几种方法
May 16 Python
python和c语言的主要区别总结
Jul 07 Python
Python Pandas 转换unix时间戳方式
Dec 07 Python
python通过matplotlib生成复合饼图
Feb 06 Python
Python读取VOC中的xml目标框实例
Mar 10 Python
Python爬取英雄联盟MSI直播间弹幕并生成词云图
Jun 01 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使用curl抓取qq空间的访客信息示例
2014/02/28 PHP
CodeIgniter生成静态页的方法
2016/05/17 PHP
Yii2中cookie用法示例分析
2016/07/18 PHP
Laravel 解决composer相关操作提示php相关异常的问题
2019/10/23 PHP
thinkphp5 框架结合plupload实现图片批量上传功能示例
2020/04/04 PHP
javascript removeChild 使用注意事项
2009/04/11 Javascript
javascript 带有滚动条的表格,标题固定,带排序功能.
2009/11/13 Javascript
基于jquery的3d效果实现代码
2011/03/23 Javascript
javascript中怎么做对象的类型判断
2013/11/11 Javascript
js 判断js函数、变量是否存在的简单示例代码
2014/03/04 Javascript
jQuery中:animated选择器用法实例
2014/12/29 Javascript
JavaScript用select实现日期控件
2015/07/17 Javascript
将页面table内容与样式另存成excel文件的方法
2015/08/05 Javascript
jQuery Validate表单验证插件 添加class属性形式的校验
2016/01/18 Javascript
JS中的hasOwnProperty()、propertyIsEnumerable()和isPrototypeOf()
2016/08/11 Javascript
BootStrap Datepicker 插件修改为默认中文的实现方法
2017/02/10 Javascript
vue-router3.0版本中 router.push 不能刷新页面的问题
2018/05/10 Javascript
Vue登录注册并保持登录状态的方法
2018/08/17 Javascript
基于vue-cli、elementUI的Vue超简单入门小例子(推荐)
2019/04/17 Javascript
解决vue中el-tab-pane切换的问题
2020/07/19 Javascript
Python中的pprint折腾记
2015/01/21 Python
简述Python中的面向对象编程的概念
2015/04/27 Python
在python中bool函数的取值方法
2018/11/01 Python
简单了解Python读取大文件代码实例
2019/12/18 Python
用Python实现定时备份Mongodb数据并上传到FTP服务器
2021/01/27 Python
CSS3 Flex 弹性布局实例代码详解
2018/11/01 HTML / CSS
旅游管理实习自我鉴定
2013/09/29 职场文书
历史学专业推荐信
2013/11/06 职场文书
大学生预备党员自我评价分享
2013/11/16 职场文书
主治医师岗位职责
2013/12/10 职场文书
中专生的个人自我评价
2013/12/11 职场文书
产品质量承诺书
2014/03/27 职场文书
党员一帮一活动总结
2014/07/08 职场文书
领导干部查摆“四风”问题自我剖析材料思想汇报
2014/10/05 职场文书
党员群众路线个人整改措施思想汇报
2014/10/12 职场文书
乡镇干部学习心得体会
2016/01/23 职场文书