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基础教程之lambda表达式使用方法
Feb 12 Python
python随机生成指定长度密码的方法
Apr 04 Python
python读取oracle函数返回值
Jul 18 Python
Python3使用正则表达式爬取内涵段子示例
Apr 22 Python
Python多线程同步---文件读写控制方法
Feb 12 Python
Python pandas实现excel工作表合并功能详解
Aug 29 Python
利用python实现AR教程
Nov 20 Python
如何基于Python实现数字类型转换
Feb 07 Python
DjangoWeb使用Datatable进行后端分页的实现
May 18 Python
Python 实现敏感目录扫描的示例代码
May 21 Python
Python类型转换的魔术方法详解
Dec 23 Python
浅谈Python响应式类库RxPy
Jun 14 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异常Parse error: syntax error, unexpected T_VAR错误解决方法
2014/05/06 PHP
ThinkPHP模型详解
2015/07/27 PHP
PHP开发中AJAX技术的简单应用
2015/12/11 PHP
PHP的PDO连接讲解
2019/01/24 PHP
PHP pthreads v3下的Volatile简介与使用方法示例
2020/02/21 PHP
比较全的JS checkbox全选、取消全选、删除功能代码
2008/12/19 Javascript
AspNet中使用JQuery上传插件Uploadify详解
2015/05/20 Javascript
js控制多图左右滚动切换效果代码分享
2015/08/26 Javascript
jQuery滚动新闻实现代码
2016/06/26 Javascript
如何用JS判断两个数字的大小
2016/07/21 Javascript
JS实现页面数据无限加载
2016/09/13 Javascript
移动端js图片查看器
2016/11/17 Javascript
babel基本使用详解
2017/02/17 Javascript
Vue框架之goods组件开发详解
2018/01/25 Javascript
集成vue到jquery/bootstrap项目的方法
2018/02/10 jQuery
解决微信小程序中转换时间格式IOS不兼容的问题
2019/02/15 Javascript
JQuery属性操作与循环用法示例
2019/05/15 jQuery
[26:40]DOTA2上海特级锦标赛A组资格赛#1 Secret VS MVP.Phx第一局
2016/02/25 DOTA
[01:10:48]完美世界DOTA2联赛PWL S2 GXR vs PXG 第一场 11.18
2020/11/18 DOTA
python中类的一些方法分析
2014/09/25 Python
跟老齐学Python之做一个小游戏
2014/09/28 Python
Python实现字符串匹配算法代码示例
2017/12/05 Python
numpy数组拼接简单示例
2017/12/15 Python
Python cookbook(数据结构与算法)根据字段将记录分组操作示例
2018/03/19 Python
python查看模块安装位置的方法
2018/10/16 Python
python使用magic模块进行文件类型识别方法
2018/12/08 Python
python字典的setdefault的巧妙用法
2019/08/07 Python
python如何保证输入键入数字的方法
2019/08/23 Python
在python中做正态性检验示例
2019/12/09 Python
python实现FTP循环上传文件
2020/03/20 Python
python根据用户需求输入想爬取的内容及页数爬取图片方法详解
2020/08/03 Python
经贸日语专业个人求职信
2013/12/13 职场文书
中学清明节活动总结
2014/07/04 职场文书
初中教师个人总结
2015/02/10 职场文书
女儿满月酒致辞
2015/07/29 职场文书
教师法制教育培训学习心得体会
2016/01/14 职场文书