0
点赞
收藏
分享

微信扫一扫

用Python写一个实时显示网速的图形程序

陈情雅雅 2022-01-27 阅读 109

需要用到库

  1. python3用tkinter, python2用Tkinter

  2. psutil

思路

  1. 利用psutil获取到第一个网卡, 然后获取传入传出的流量, 单位是字节(byte), 一般都是KB, 也就是一千个字节来显示比较普遍, 所以后面有除以1024;

  2. 用while循环, 每隔一秒来刷新;

  3. tkinter中按钮绑定的方法作为一个中间方法, 先开启一个线程, 然后在执行实际的代码, 这样图形界面也不会卡顿.

下面是实际的代码

# _*_ coding: utf-8 _*_
# @Author : otfsenter

try:
    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_recv
    out_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 = event
        self.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) / 1024
            net_out = (out_new - out_old) / 1024
            net_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_new
            out_old = out_new

if __name__ == '__main__':
    Window()

举报

相关推荐

0 条评论