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

效果圖:這個也太醜了,下次搞個好看一點的 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章