使用 Python 和 PyQt5 构建一个 带图标的任务管理器 附源码

在本博客中,我将分享如何使用 Python 和 PyQt5 构建一个简单的任务管理器应用程序。此应用程序可以显示所有运行中的进程,并提供一个按钮来终止每个进程。此外,每个进程还显示其关联的图标。这将是一个非常有趣的项目,可以帮助您更好地理解 Python 和 PyQt5 的实际应用。

环境准备

在开始之前,您需要确保安装了以下 Python 包:

  • psutil
  • Pillow
  • pywin32
  • PyQt5

您可以使用以下命令来安装这些包:

pip install psutil Pillow pywin32 PyQt5

代码片段解析与使用步骤

1. 导入必要的库

首先,我们需要导入一些必要的库:

import sys
import os
import ctypes
import psutil
import win32gui
import win32ui
import win32process
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QLabel, QPushButton, QWidget, QScrollArea, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QImage
from PIL import Image

这些库包括系统操作、图形界面、进程管理等功能。

2. 提取图标函数

定义一个函数 extract_icon(exe_path) 来提取可执行文件的图标:

def extract_icon(exe_path):
    try:
        large, small = win32gui.ExtractIconEx(exe_path, 0)
        hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
        hbmp = win32ui.CreateBitmap()
        hbmp.CreateCompatibleBitmap(hdc, 32, 32)
        hdc = hdc.CreateCompatibleDC()
        hdc.SelectObject(hbmp)
        hdc.DrawIcon((0, 0), large[0])

        # 保存图标
        hbmpinfo = hbmp.GetInfo()
        hbmpstr = hbmp.GetBitmapBits(True)
        img = Image.frombuffer(
            'RGBA',
            (hbmpinfo['bmWidth'], hbmpinfo['bmHeight']),
            hbmpstr, 'raw', 'BGRA', 0, 1
        )

        # 释放资源
        win32gui.DestroyIcon(large[0])
        win32gui.DestroyIcon(small[0])

        return img
    except Exception as e:
        print(f"Error extracting icon from {exe_path}: {e}")
        return None

这个函数从可执行文件中提取图标,并将其转换为 PIL 图像对象。

3. 创建主窗口类

定义一个 ProcessManager 类来创建主窗口:

class ProcessManager(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(100, 100, 800, 600)
        self.setWindowTitle('任务管理器')

        self.central_widget = QWidget()
        self.layout = QVBoxLayout(self.central_widget)

        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_content = QWidget()
        self.scroll_layout = QVBoxLayout(self.scroll_content)

        self.scroll_area.setWidget(self.scroll_content)
        self.layout.addWidget(self.scroll_area)

        self.central_widget.setLayout(self.layout)
        self.setCentralWidget(self.central_widget)

        self.load_processes()

这个类初始化了主窗口,并设置了滚动区域来显示进程信息。

4. 加载进程信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LIY若依

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值