Python网络流量检测

import psutil
import time
import tkinter
from PIL import Image, ImageTk

def network_state():        #实时流量
    bytes_sent1 = psutil.net_io_counters(pernic=True)['WLAN'].bytes_sent
    bytes_recv1 = psutil.net_io_counters(pernic=True)['WLAN'].bytes_recv
    #print(bytes_sent1,bytes_recv1)
    time.sleep(1)

    bytes_sent2 = psutil.net_io_counters(pernic=True)['WLAN'].bytes_sent
    bytes_recv2 = psutil.net_io_counters(pernic=True)['WLAN'].bytes_recv

    sent_rate = bytes_sent2 - bytes_sent1
    recv_rate = bytes_recv2 - bytes_recv1

    if sent_rate < 1024 and recv_rate < 1024:
        L1.configure(text=str(sent_rate)+' B/s')  # 重新设置标签文本
        L2.configure(text=str(recv_rate)+' B/s')
        root.after(1000, network_state)            # 每隔1s调用函数network_state
                                                   # tkinter窗口,比如root窗口,有一个after方法。此方法执行后,将会在规定的时间间隔之后,执行一个您指定的函数
    elif sent_rate > 1024 or recv_rate > 1024:
        sent_rate = round((bytes_sent2 - bytes_sent1) / 1024, 1)
        recv_rate = round((bytes_recv2 - bytes_recv1) / 1024, 1)
        L1.configure(text=str(sent_rate) + ' kB/s')
        L2.configure(text=str(recv_rate) + ' kB/s')
        root.after(1000, network_state)
    else:
        sent_rate = round((bytes_sent2 - bytes_sent1) / 1024 / 1024, 1)
        recv_rate = round((bytes_recv2 - bytes_recv1) / 1024 /1024 , 1)
        L1.configure(text=str(sent_rate) + ' MB/s')
        L2.configure(text=str(recv_rate) + ' MB/s')
        root.after(1000, network_state)


def mouse_enter(event):     #光标进入标签控件触发
    root.withdraw()
    time.sleep(1)

def mouse_leave(event):     #光标离开标签控件触发
    root.deiconify()


if __name__ == '__main__':
    root = tkinter.Tk()
    root.title('网速')
    root.iconbitmap("wifi_single.ico")
    root.geometry('150x60+1100+60')    #设置窗体的大小(200x100),与出现的位置距离窗体左上角(+1100+60)
    # root["background"] = "#f1f1f1"
    root.resizable(0, 0)

    L1 = tkinter.Label(root, text='', fg='black', font=("黑体", 16))
    L1.grid(row=0, column=1)
    L2 = tkinter.Label(root, text='', fg='black', font=("黑体", 16))
    L2.grid(row=1, column=1)

    img_open1 = Image.open('up.png')
    img_png1 = ImageTk.PhotoImage(img_open1)
    L3 = tkinter.Label(root, width=30, image=img_png1)
    L3.grid(row=0,column=0)

    img_open2 = Image.open('down.png')
    img_png2 = ImageTk.PhotoImage(img_open2)
    L4 = tkinter.Label(root, width=30, image=img_png2)
    L4.grid(row=1,column=0)

    L3.bind('<Enter>', mouse_enter)      #绑定事件
    L3.bind('<Leave>', mouse_leave)
    L4.bind('<Enter>', mouse_enter)
    L4.bind('<Leave>', mouse_leave)

    network_state()
    root.mainloop()

效果图


20200625151855143.png

————————————————
版权声明:本文为CSDN博主「割韭菜i」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_45670433/article/details/106958409[图片上传中...(20200625151855143.png-300dab-1675058004129-0)]

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容