Tkinter实现实时显示本机网络速度

Tkinter实现椭圆形半透明窗口实时显示本机网络速度


需要用到的库:

import tkinter
from time import sleep
from threading import Thread
from psutil import net_io_counters
from PIL import Image, ImageTk, ImageDraw

 设置TK的参数:

width, height = 160, 80
root = tkinter.Tk()
root.geometry(f'{width}x{height}+1300+650')
root.resizable(False, False)
root.overrideredirect(True)
root.attributes('-transparentcolor', 'white')
root.attributes('-topmost', True)
image = Image.new('RGBA', (width, height), (255, 255, 255, 255))
draw = ImageDraw.Draw(image)
draw.ellipse((0, 0, width, height), fill=(200, 200, 200, 30))
image_tk = ImageTk.PhotoImage(image)
lbTraffic = tkinter.Label(root, text="", font=('楷体', 14), foreground='blue', bg='#ffffff', compound=tkinter.CENTER, anchor='center', image=image_tk)
lbTraffic.place(x=0, y=0, width=width, height=height)
canMove = tkinter.BooleanVar(root, False)
X = tkinter.IntVar(root, value=0)
Y = tkinter.IntVar(root, value=0)

实现方法:

def onLeftButtonDown(event):
    X.set(event.x)
    Y.set(event.y)
    canMove.set(True)


root.bind('<Button-1>', onLeftButtonDown)
def onLeftButtonup(event):
    canMove.set(True)


root.bind('<ButtonRelease-1>', onLeftButtonup)
def onLeftButtonMove(event):
    if not canMove.get():
        return
    newX = root.winfo_x() + (event.x - X.get())
    newY = root.winfo_y() + (event.y - Y.get())
    g = f'{width}x{height}+{newX}+{newY}'
    root.geometry(g)


root.bind('<B1-Motion>', onLeftButtonMove)
def onRightButtonUp(event):
    running.set(False)
    root.destroy()


root.bind('<ButtonRelease-3>', onRightButtonUp)
def computer_traffic():
    traffic_io = net_io_counters()[:2]
    while running.get():
        sleep(0.5)
        traffic_ioNew = net_io_counters()[:2]
        diff = tuple(map(lambda x, y: (x - y) * 2 / 1024, traffic_ioNew, traffic_io))
        msg = '↑:{:.2f}KB/s\n↓:{:.2f}KB/s'.format(*diff)
        lbTraffic['text'] = msg
        traffic_io = traffic_ioNew

running = tkinter.BooleanVar(root,True)
Thread(target = compute_traffic).star()
root.mainloop()

效果图:这个也太丑了,下次搞个好看一点的 

评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值