如何使用Python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的window任務(wù)管理器
任務(wù)管理器效果圖

完整代碼
import tkinter as tk
from tkinter import ttk
import psutil
# 運(yùn)行此代碼前,請(qǐng)確保已經(jīng)安裝了 psutil 庫(kù),可以使用 pip install psutil 進(jìn)行安裝。
# 由于獲取進(jìn)程信息可能會(huì)受到權(quán)限限制,某些進(jìn)程的信息可能無(wú)法獲取,代碼中已經(jīng)對(duì)可能出現(xiàn)的異常進(jìn)行了處理。
def get_process_info():
process_list = []
for proc in psutil.process_iter(['pid', 'name', 'memory_percent']):
try:
pid = proc.info['pid']
name = proc.info['name']
mem_percent = proc.info['memory_percent']
process_list.append((pid, name, f'{mem_percent:.2f}%'))
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
return process_list
def populate_table():
for item in process_table.get_children():
process_table.delete(item)
processes = get_process_info()
for pid, name, mem_percent in processes:
mem_value = float(mem_percent.strip('%'))
tag = ""
if mem_value > 10:
tag = "high_mem"
elif mem_value > 5:
tag = "medium_mem"
process_table.insert('', 'end', values=(pid, name, mem_percent), tags=(tag,))
# 設(shè)置標(biāo)簽樣式
process_table.tag_configure("high_mem", foreground="red")
process_table.tag_configure("medium_mem", foreground="green")
def sort_table(column, reverse):
data = [(process_table.set(item, column), item) for item in process_table.get_children('')]
if column == 'PID':
data.sort(key=lambda t: int(t[0]), reverse=reverse)
elif column == '內(nèi)存占用率':
data.sort(key=lambda t: float(t[0].strip('%')), reverse=reverse)
else:
data.sort(key=lambda t: t[0], reverse=reverse)
for index, (_, item) in enumerate(data):
process_table.move(item, '', index)
process_table.heading(column, command=lambda: sort_table(column, not reverse))
root = tk.Tk()
root.title("任務(wù)管理器")
root.geometry("700x500")
root.configure(bg="#f4f4f9")
style = ttk.Style()
style.theme_use('clam')
style.configure('Treeview', background="#e9e9f3", foreground="#333", fieldbackground="#e9e9f3",
rowheight=25, font=('Segoe UI', 10))
style.map('Treeview', background=[('selected', '#73a6ff')])
style.configure('Treeview.Heading', background="#d1d1e0", foreground="#333", font=('Segoe UI', 10, 'bold'))
columns = ('PID', '進(jìn)程名稱', '內(nèi)存占用率')
process_table = ttk.Treeview(root, columns=columns, show='headings')
for col in columns:
process_table.heading(col, text=col, command=lambda c=col: sort_table(c, False))
process_table.column(col, width=200, anchor='center')
process_table.pack(pady=20, padx=20, fill=tk.BOTH, expand=True)
populate_table()
refresh_button = ttk.Button(root, text="刷新", command=populate_table)
refresh_button.pack(pady=10)
root.mainloop()方法擴(kuò)展
Python調(diào)用Windows API實(shí)現(xiàn)任務(wù)管理器功能
任務(wù)管理器具體功能有:
1、 列出系統(tǒng)當(dāng)前所有進(jìn)程。
2、 列出隸屬于該進(jìn)程的所有線程。
3、 如果進(jìn)程有窗口,可以顯示和隱藏窗口。
4、 強(qiáng)行結(jié)束指定進(jìn)程。
通過(guò)Python調(diào)用Windows API還是很實(shí)用的,能夠結(jié)合Python的簡(jiǎn)潔和Windows API的強(qiáng)大,寫出各種各樣的腳本。
編碼中的幾個(gè)難點(diǎn)有:
調(diào)用API的具體方式是什么?
答:通過(guò)win32模塊或ctypes模塊。前者更簡(jiǎn)便,后者函數(shù)庫(kù)更全。
不熟悉Windows API怎么辦?
通過(guò)API伴侶這個(gè)軟件查詢API所在的DLL庫(kù),通過(guò)MSDN查詢API的詳細(xì)解釋等等。
完整代碼如下:
import os
# import win32api
import win32gui
import win32process
from ctypes import *
# 列出系統(tǒng)當(dāng)前所有進(jìn)程。
def getProcessList():
os.system("tasklist")
# 結(jié)構(gòu)體
class THREADENTRY32(Structure):
_fields_ = [('dwSize', c_ulong),
('cntUsage', c_ulong),
('th32ThreadID', c_ulong),
('th32OwnerProcessID', c_ulong),
('tpBasePri', c_long),
('tpDeltaPri', c_long),
('dwFlags', c_ulong)]
# 獲取指定進(jìn)程的所有線程
def getThreadOfProcess(pid):
dll = windll.LoadLibrary("KERNEL32.DLL")
snapshotHandle = dll.CreateToolhelp32Snapshot(0x00000004, pid)
struct = THREADENTRY32()
struct.dwSize = sizeof(THREADENTRY32)
flag = dll.Thread32First(snapshotHandle, byref(struct))
while flag != 0:
if(struct.th32OwnerProcessID == int(pid)):
print("線程id:"+str(struct.th32ThreadID))
flag = dll.Thread32Next(snapshotHandle, byref(struct))
dll.CloseHandle(snapshotHandle)
# EnumWindows的回調(diào)函數(shù)
def callback(hwnd, windows):
pidList = win32process.GetWindowThreadProcessId(hwnd)
for pid in pidList:
windows.setdefault(pid, [])
windows[pid].append(hwnd)
# 顯示和隱藏指定進(jìn)程的窗口
def changeWindowState(pid, status):
windows = {}
win32gui.EnumWindows(callback, windows)
try:
hwndList = windows[int(pid)]
# 顯示/隱藏窗口
for hwnd in hwndList:
win32gui.ShowWindow(hwnd, int(status))
except:
print("進(jìn)程不存在")
# 強(qiáng)行結(jié)束指定進(jìn)程
def killProcess(pid):
cmd = 'taskkill /pid ' + pid + ' /f'
try:
os.system(cmd)
except Exception as e:
print(e)
if __name__ == "__main__":
while(True):
print()
print()
print("************************************")
print("* *")
print("* 進(jìn)程管理器 *")
print("* *")
print("* 1.獲取所有進(jìn)程 *")
print("* 2.獲取指定進(jìn)程的所有線程 *")
print("* 3.顯示和隱藏指定進(jìn)程的窗口 *")
print("* 4.強(qiáng)行結(jié)束指定進(jìn)程 *")
print("* *")
print("************************************")
option = input("請(qǐng)選擇功能:")
if option == "1":
getProcessList()
elif option == "2":
pid = input("請(qǐng)輸入進(jìn)程的pid:")
getThreadOfProcess(pid)
elif option == "3":
pid = input("請(qǐng)輸入進(jìn)程的pid:")
status = input("隱藏輸入0,顯示輸入1:")
changeWindowState(pid, status)
elif option == "4":
pid = input("請(qǐng)輸入進(jìn)程的pid:")
killProcess(pid)
else:
exit()到此這篇關(guān)于如何使用Python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的window任務(wù)管理器的文章就介紹到這了,更多相關(guān)Python任務(wù)管理器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python panda庫(kù)從基礎(chǔ)到高級(jí)操作分析
本文介紹了Pandas庫(kù)的核心功能,包括處理結(jié)構(gòu)化數(shù)據(jù)的Series和DataFrame數(shù)據(jù)結(jié)構(gòu),數(shù)據(jù)讀取、清洗、分組聚合、合并、時(shí)間序列分析及大數(shù)據(jù)優(yōu)化技巧,強(qiáng)調(diào)其高效性、靈活性和與科學(xué)計(jì)算庫(kù)的集成能力,感興趣的朋友跟隨小編一起看看吧2025-08-08
python創(chuàng)建多個(gè)logging日志文件的方法實(shí)現(xiàn)
本文主要介紹了python創(chuàng)建多個(gè)logging日志文件的方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
Python填充任意顏色,不同算法時(shí)間差異分析說(shuō)明
這篇文章主要介紹了Python填充任意顏色,不同算法時(shí)間差異分析說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05
Python中選擇排序的實(shí)現(xiàn)與優(yōu)化
選擇排序(Selection?Sort)是一種簡(jiǎn)單但有效的排序算法,本文將詳細(xì)介紹選擇排序算法的原理和實(shí)現(xiàn),并提供相關(guān)的Python代碼示例,需要的可以參考一下2023-06-06
一文詳解Python函數(shù)定義的12個(gè)參數(shù)傳遞技巧
在Python中,函數(shù)是代碼復(fù)用的核心工具,這篇文章主要為大家詳細(xì)介紹了Python函數(shù)定義的12個(gè)參數(shù)傳遞技巧,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下2026-02-02
創(chuàng)建Python Docker鏡像的詳細(xì)步驟
Python和Docker是兩個(gè)極其流行的技術(shù),結(jié)合它們可以創(chuàng)建強(qiáng)大的應(yīng)用程序,Docker允許將應(yīng)用程序及其依賴項(xiàng)打包到一個(gè)獨(dú)立的容器中,而Python則提供了豐富的庫(kù)和工具來(lái)開(kāi)發(fā)應(yīng)用程序,本文將提供如何創(chuàng)建Python Docker鏡像的全面指南,,需要的朋友可以參考下2023-12-12
Python中使用__new__實(shí)現(xiàn)單例模式并解析
單例模式是一個(gè)經(jīng)典設(shè)計(jì)模式,簡(jiǎn)要的說(shuō),一個(gè)類的單例模式就是它只能被實(shí)例化一次,實(shí)例變量在第一次實(shí)例化時(shí)就已經(jīng)固定。 這篇文章主要介紹了Python中使用__new__實(shí)現(xiàn)單例模式并解析 ,需要的朋友可以參考下2019-06-06
Python使用XlsxWriter生成Excel并自動(dòng)輸出統(tǒng)計(jì)報(bào)表
很多 Python 學(xué)習(xí)者在接觸辦公自動(dòng)化時(shí),都會(huì)很自然地想到一個(gè)需求:能不能用 Python 批量處理 Excel,并自動(dòng)生成一份像樣的統(tǒng)計(jì)報(bào)表?這篇文章會(huì)帶你系統(tǒng)掌握 XlsxWriter 的核心用法,并通過(guò)一個(gè)完整案例,學(xué)會(huì)如何自動(dòng)生成一份統(tǒng)計(jì)報(bào)表,需要的朋友可以參考下2026-05-05

