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中查找excel某一列的重复数据 剔除之后打印
Feb 10 Python
跟老齐学Python之永远强大的函数
Sep 14 Python
利用Python的装饰器解决Bottle框架中用户验证问题
Apr 24 Python
Python的IDEL增加清屏功能实例
Jun 19 Python
Python复制Word内容并使用格式设字体与大小实例代码
Jan 22 Python
python如何查看微信消息撤回
Nov 27 Python
python 对类的成员函数开启线程的方法
Jan 22 Python
Python的UTC时间转换讲解
Feb 26 Python
django2.2 和 PyMySQL版本兼容问题
Feb 17 Python
Python操作MongoDb数据库流程详解
Mar 05 Python
浅析Python模块之间的相互引用问题
Feb 26 Python
如何在Python中创建二叉树
Mar 30 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
How do I change MySQL timezone?
2008/03/26 PHP
PHP定时执行任务实现方法详解(Timer)
2015/07/30 PHP
php商品对比功能代码分享
2015/09/24 PHP
PHP使用SOAP扩展实现WebService的方法
2016/04/01 PHP
PHP数组操作简单案例分析
2016/10/15 PHP
JS DOM 操作实现代码
2010/08/01 Javascript
弹出层之1:JQuery.Boxy (一) 使用介绍
2011/10/06 Javascript
Prototype源码浅析 Enumerable部分(二)
2012/01/18 Javascript
JS中如何设置readOnly的值
2013/12/25 Javascript
javascript中String对象的slice()方法分析
2014/12/20 Javascript
js给selected添加options的方法
2015/05/06 Javascript
不想让浏览器运行javascript脚本的方法
2015/11/20 Javascript
Bootstrap+jfinal退出系统弹出确认框的实现方法
2016/05/30 Javascript
jQuery获取多种input值的简单实现方法
2016/06/20 Javascript
jquery实现搜索框功能实例详解
2018/07/23 jQuery
浅谈微信页面入口文件被缓存解决方案
2018/09/29 Javascript
对angularJs中2种自定义服务的实例讲解
2018/09/30 Javascript
vue eslint简要配置教程详解
2019/07/26 Javascript
vue.js 2.0实现简单分页效果
2019/07/29 Javascript
浅谈vue的第一个commit分析
2020/06/08 Javascript
[00:52]黑暗之门更新 新英雄孽主驾临DOTA2
2016/08/24 DOTA
python 参数列表中的self 显式不等于冗余
2008/12/01 Python
Python的Flask框架中实现简单的登录功能的教程
2015/04/20 Python
Python实现合并字典的方法
2015/07/07 Python
Python的Flask开发框架简单上手笔记
2015/11/16 Python
python利用正则表达式排除集合中字符的功能示例
2017/10/10 Python
对django xadmin自定义菜单的实例详解
2019/01/03 Python
Python的matplotlib绘图如何修改背景颜色的实现
2019/07/16 Python
Django Serializer HiddenField隐藏字段实例
2020/03/31 Python
为什么python比较流行
2020/06/19 Python
全球500多个机场的接送服务:Suntransfers
2019/06/03 全球购物
幼儿园保育员责任书
2014/07/22 职场文书
检察机关个人对照检查材料
2014/09/15 职场文书
2014学校领导四风对照检查材料思想汇报
2014/09/23 职场文书
投诉信回复范文
2015/07/03 职场文书
SpringBoot2零基础到精通之数据与页面响应
2022/03/22 Java/Android