有时我们只是想要一个速的工具来告诉当前疫情的情况,我们只需要最少的数据。 使用Python语言和tkinter图形化显示数据。 |
首先,我们使用 Tkinter
库使我们的脚本可以图形化显示。
使用 requests
库从 丁香园 获取数据。
然后我们将在这种情况下显示我们需要的数据 “当前确诊人数”,“总确诊人数”。
需求和安装
ssh客户端为:MobaXterm,因为它支持X11-Forwarding
系统:Centos8 Minimal
Python版本:Python3.6.8
需要用到的库:requests
, json
, tkinter
, time
下面来安装xorg,用来在远程终端中打开图形化界面,安装python3-tkinter来创建GUI界面:
[root@localhost data]# yum -y install xorg-x11-xauth xorg-x11-utils python3-tkinter
上脚本
下面创建python脚本:
[root@localhost data]# touch gui.py [root@localhost data]# chmod +x gui.py [root@localhost data]# vim gui.py#!/usr/bin/python3# 导入time, requests, json, tkinter库 import time import requests import json from tkinter import *# 创建一个窗口 window = Tk()# 窗口标题为“Covid-19” window.title("Covid-19")# 窗口大小为600px * 130px window.geometry('600x130')# 创建label 1,并创建初始信息 lbl = Label(window, text = "The number of confirmed cases in China: ....") # label窗格占用第1列,第1行,靠左对齐。 lbl.grid(column = 1, row = 0, sticky = W)# 创建label 2,并创建初始信息 lbl1 = Label(window, text = "Cumulative number of confirmed cases in China: ....") lbl1.grid(column = 1, row = 1, sticky = W)# 创建label 3,并创建初始信息,用来显示时间的。 lbl2 = Label(window, text = "Data update time: ....") lbl2.grid(column = 1, row = 3, sticky = W)# 创建label 4,并创建初始信息,用来显示是否刷新。 lbl3 = Label(window, fg = 'green', text = "") lbl3.grid(column = 1, row = 4, sticky = W)# 定义一个点击事件 def clicked():# 制定API接口的地址url = "https://lab.isaaclin.cn/nCoV/api/overall"# 获取url地址page = requests.get(url)# 将json数据载入内存data = json.loads(page.text)#下面4个变量用来将API中的时间戳转化为时间。tm = data["results"][0]["updateTime"]timeStamp = float(tm/1000)timeArray = time.localtime(timeStamp)updatetime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)# 当点击时,获取 currentConfirmedCount 的值,因为text里面只能用str字符串,所以需要将证书类型的数字转化为字符串。lbl.configure(text ="The number of confirmed cases in China: " + "%s" %(data["results"][0]["currentConfirmedCount"]))lbl1.configure(text ="Cumulative number of confirmed cases in China: " + "%s" %(data["results"][0]["confirmedCount"]))lbl2.configure(text ="Data update time: " + updatetime)lbl3.configure(text ="State: Refresh")# 创建一个按钮,用来刷新数据。 btn = Button(window, text ="Refresh", command = clicked) # 按钮的位置在第2列,第5行。 btn.grid(column = 2, row = 5)# 显示窗口 window.mainloop()
解释:
sticky =
对齐方式的值有四个,N, S, W, E,代表着东西南北、上下左右。执行脚本,输出如下内容:
[root@localhost data]# ./gui.py
点击Refresh之后,会看到获取的数据啦。