You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:优化Python实现的Windows电脑信息悬浮监控工具

Windows 右上角电脑信息监控工具优化实现(Tkinter版)

问题概述

当前实现存在以下问题:

  • 界面:背景透明度不符合预期,字体样式无法满足需求
  • 功能:缺少资源高占用告警机制(如字体变色、弹窗提示),信息展示冗余不够简洁
  • 性能:工具无法正常运行,存在线程安全及循环逻辑问题

原始代码

import psutil
import tkinter as tk
import threading

def get_cpu_usage():
    cpu_percent = psutil.cpu_percent(interval=1)
    return f"CPU: {cpu_percent}%"

def get_memory_usage():
    mem = psutil.virtual_memory()
    mem_percent = mem.percent
    mem_total = round(mem.total / (1024 ** 3), 2)
    mem_used = round(mem.used / (1024 ** 3), 2)
    return f"Memory: {mem_used}GB / {mem_total}GB ({mem_percent}%)"

def update_taskbar_label(label):
    while True:
        cpu_text = get_cpu_usage()
        mem_text = get_memory_usage()
        label.config(text=f"{cpu_text}   {mem_text}")
        label.update_idletasks()

def close_window(event):
    root.destroy()

def main():
    root = tk.Tk()
    root.title("Taskbar Monitor")

    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()

    window_width = 512
    window_height = 64

    x = screen_width - window_width
    y = screen_height - window_height - 64

    root.geometry(f"{window_width}x{window_height}+{x}+{y}")
    root.overrideredirect(True)
    root.attributes("-alpha", 0.7)

    label = tk.Label(root, font=("Msyh", 14))
    label.pack(expand=True, fill=tk.BOTH)

    thread = threading.Thread(target=update_taskbar_label, args=(label,))
    thread.daemon = True
    thread.start()

    root.bind("<Escape>", close_window)

    root.mainloop()

if __name__ == "__main__":
    main()

优化后的代码

import psutil
import tkinter as tk
from tkinter import messagebox

# 配置参数
ALERT_THRESHOLD_CPU = 80  # CPU告警阈值(%)
ALERT_THRESHOLD_MEM = 85  # 内存告警阈值(%)
UPDATE_INTERVAL = 1000    # 更新间隔(毫秒)
WINDOW_OPACITY = 0.8      # 窗口透明度
FONT_STYLE = ("微软雅黑", 12, "bold")
WINDOW_SIZE = "350x50"

class SystemMonitor:
    def __init__(self, root):
        self.root = root
        self.setup_window()
        self.setup_widgets()
        self.last_net_io = psutil.net_io_counters()
        self.alert_shown = {"cpu": False, "mem": False}
        self.update_monitor()

    def setup_window(self):
        self.root.title("系统监控")
        self.root.overrideredirect(True)
        self.root.attributes("-alpha", WINDOW_OPACITY)
        self.root.attributes("-topmost", True)  # 窗口置顶

        # 固定到屏幕右上角
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_width = int(WINDOW_SIZE.split("x")[0])
        window_height = int(WINDOW_SIZE.split("x")[1])
        x_pos = screen_width - window_width - 10  # 留10px边距
        y_pos = 10  # 顶部留10px边距
        self.root.geometry(f"{WINDOW_SIZE}+{x_pos}+{y_pos}")

        # 允许拖动窗口
        self.root.bind("<ButtonPress-1>", self.start_drag)
        self.root.bind("<B1-Motion>", self.drag_window)
        self.root.bind("<Escape>", self.close_window)

    def setup_widgets(self):
        self.monitor_label = tk.Label(
            self.root,
            font=FONT_STYLE,
            bg="#2c3e50",
            fg="#ecf0f1",
            padx=10,
            pady=5
        )
        self.monitor_label.pack(expand=True, fill=tk.BOTH)

    def get_cpu_data(self):
        cpu_percent = psutil.cpu_percent()
        # 判断是否触发告警
        if cpu_percent >= ALERT_THRESHOLD_CPU:
            if not self.alert_shown["cpu"]:
                messagebox.showwarning("告警", f"CPU使用率过高:{cpu_percent}%")
                self.alert_shown["cpu"] = True
            return f"C: {cpu_percent}%", "#e74c3c"  # 红色字体
        else:
            self.alert_shown["cpu"] = False
            return f"C: {cpu_percent}%", "#ecf0f1"  # 默认白色字体

    def get_memory_data(self):
        mem = psutil.virtual_memory()
        mem_percent = mem.percent
        mem_used_gb = round(mem.used / (1024**3), 1)
        # 简化展示
        if mem_percent >= ALERT_THRESHOLD_MEM:
            if not self.alert_shown["mem"]:
                messagebox.showwarning("告警", f"内存使用率过高:{mem_percent}%")
                self.alert_shown["mem"] = True
            return f"M: {mem_used_gb}GB ({mem_percent}%)", "#e74c3c"
        else:
            self.alert_shown["mem"] = False
            return f"M: {mem_used_gb}GB ({mem_percent}%)", "#ecf0f1"

    def get_network_speed(self):
        current_net_io = psutil.net_io_counters()
        send_speed = round((current_net_io.bytes_sent - self.last_net_io.bytes_sent) / 1024 / UPDATE_INTERVAL * 1000, 1)
        recv_speed = round((current_net_io.bytes_recv - self.last_net_io.bytes_recv) / 1024 / UPDATE_INTERVAL * 1000, 1)
        self.last_net_io = current_net_io
        return f"↑{send_speed}KB/s ↓{recv_speed}KB/s"

    def update_monitor(self):
        cpu_text, cpu_color = self.get_cpu_data()
        mem_text, mem_color = self.get_memory_data()
        net_text = self.get_network_speed()

        # 组合文本,设置对应颜色
        full_text = f"{cpu_text} | {mem_text} | {net_text}"
        self.monitor_label.config(text=full_text)
        # 统一用告警色(如果任一触发)
        self.monitor_label.config(fg=cpu_color if cpu_color == "#e74c3c" else mem_color)

        # 用Tkinter的after方法循环更新,避免线程问题
        self.root.after(UPDATE_INTERVAL, self.update_monitor)

    def start_drag(self, event):
        self.drag_x = event.x
        self.drag_y = event.y

    def drag_window(self, event):
        x = self.root.winfo_x() + event.x - self.drag_x
        y = self.root.winfo_y() + event.y - self.drag_y
        self.root.geometry(f"+{x}+{y}")

    def close_window(self, event):
        self.root.destroy()

if __name__ == "__main__":
    root = tk.Tk()
    app = SystemMonitor(root)
    root.mainloop()

优化说明

  1. 界面优化

    • 调整窗口位置到右上角,增加边距避免紧贴屏幕边缘
    • 可自定义透明度、字体样式,设置深色背景提升可读性
    • 支持窗口拖动,方便用户调整位置
    • 修复原代码中root作用域问题,确保关闭功能正常
  2. 功能增强

    • 新增网速监控(上传/下载速度)
    • 加入CPU、内存使用率告警:超过阈值时弹出提示框,同时字体变红
    • 简化信息展示:用简写符号(C=CPU、M=内存),去掉冗余描述,提升简洁度
  3. 性能修复

    • 替换原线程循环为Tkinter原生after方法,避免线程安全问题,提升稳定性
    • 调整CPU使用率获取方式(去掉interval=1),配合定时更新避免阻塞
    • 优化网络速度计算逻辑,基于时间间隔动态计算,更准确

内容的提问来源于stack exchange,提问作者Lingyi_Bit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:46:02