作者:梦露的殇_192 | 来源:互联网 | 2023-09-17 23:50
需要用到库python3用tkinter,python2用Tkinterpsutil思路利用psutil获取到第一个网卡,然后获取传入传出的流量,单位是字节(byte),一般都是
需要用到库
-
python3用tkinter, python2用Tkinter
-
psutil
思路
-
利用psutil获取到第一个网卡, 然后获取传入传出的流量, 单位是字节(byte), 一般都是KB, 也就是一千个字节来显示比较普遍, 所以后面有除以1024;
-
用while循环, 每隔一秒来刷新;
-
tkinter中按钮绑定的方法作为一个中间方法, 先开启一个线程, 然后在执行实际的代码, 这样图形界面也不会卡顿.
下面是实际的代码
# _*_ coding: utf-8 _*_
# @Author : otfsentertry:import Tkinter as tk
except ImportError:import tkinter as tk
import threading
import time
import psutil# 最后的1表示第2个网卡,如果网速显示不正常,可以尝试变化一下数字,一般是1
key = list(psutil.net_io_counters(pernic=True).keys())[2]def seconds():in_flow = psutil.net_io_counters(pernic=True).get(key).bytes_recvout_flow = psutil.net_io_counters(pernic=True).get(key).bytes_sent return int(in_flow), int(out_flow)class Window(tk.Tk):def __init__(self):tk.Tk.__init__(self)# self.event = eventself.geometry('200x90')self.val_in = tk.StringVar()self.val_out = tk.StringVar()self.label_in = tk.Label(self, text='Incoming')self.label_out = tk.Label(self, text='Outgoing')self.entry_in = tkinter.Entry(self, textvariable=self.val_in)self.entry_out = tkinter.Entry(self, textvariable=self.val_out)self.button = tkinter.Button(self, text='Start!',command=self.judge)self.label_in.grid(row=0, column=0)self.label_out.grid(row=1, column=0)self.entry_in.grid(row=0, column=1)self.entry_out.grid(row=1, column=1)self.button.grid(row=2, column=0)self.mainloop()def judge(self):t = threading.Thread(target=self.schedule)t.start()def schedule(self):in_old, out_old = seconds()while 1:time.sleep(1)in_new, out_new = seconds()net_in = (in_new - in_old) / 1024net_out = (out_new - out_old) / 1024net_in = str(net_in).split('.')[0] + '.' + str(net_in).split('.')[1][:2]net_out = str(net_out).split('.')[0] + '.' + str(net_out).split('.')[1][:2]self.val_in.set(str(net_in) + 'KB/s')self.val_out.set(str(net_out) + 'KB/s')in_old = in_newout_old = out_newif __name__ == '__main__':Window()