共计 2077 个字符,预计需要花费 6 分钟才能阅读完成。
导读 | 有时我们只是想要一个速的工具来告诉当前疫情的情况,我们只需要最少的数据。使用 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 之后,会看到获取的数据啦。
正文完
星哥玩云-微信公众号
