在本博客中,我将分享如何使用 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()
这个类初始化了主窗口,并设置了滚动区域来显示进程信息。