xupengfei 6 months ago
parent 75c20d4b51
commit cb66d6e67e

@ -1,5 +1,3 @@
import mysql.connector
from mysql.connector import Error
from math import *
import tkinter as t
import psutil
@ -7,56 +5,13 @@ import os
import time
import threading
import datetime
db_config = {
'host': 'localhost',
'user': 'root',
'password': '2015wocani',
'database': 'ProcessData'
}
def init_db_connection():
global db_connection, cursor
try:
db_connection = mysql.connector.connect(**db_config)
cursor = db_connection.cursor()
print("Database connection successful")
except Error as e:
print(f"Error connecting to MySQL: {e}")
# 关闭数据库连接
def close_db_connection():
if db_connection.is_connected():
cursor.close()
db_connection.close()
print("MySQL connection is closed")
def get_db_cursor(connection):
"""获取并返回数据库游标"""
return connection.cursor()
db_connection = create_db_connection(**db_config)
# 定义获取游标的函数
def get_db_cursor(connection):
return connection.cursor()
# 使用上面创建的连接来获取游标
db_cursor = get_db_cursor(db_connection)
root= t.Tk() #主窗口
root.title('任务管理器') #标题
root.geometry('730x630') #窗口尺寸
root.iconbitmap('1.ico') #窗口图标 必须是ico格式的图片
root.resizable(width=True, height=True)# 设置窗口宽度,高度可变
root.attributes('-alpha',0.9) #设置窗口透明度
root.wm_attributes('-topmost',1) #实现root窗口的置顶显示
sb=t.Scrollbar(root)
sb.pack(side='left',fill='y')
text=t.Text(root,width=100,height=40)
@ -71,49 +26,22 @@ t1.place(x=10,y=580,width=120)
t2.place(x=150,y=580,width=120)
t3.place(x=300,y=580,width=120)
def create_db_connection():
connection = pymysql.connect(host='localhost', user='root', password='2015wocani', database='ProcessData')
return connection
db_connection = create_db_connection(**db_config)
db_cursor = get_db_cursor(db_connection)
def insert_process(pid, name, path, mem_usage, cpu_usage):
"""插入进程数据到数据库"""
try:
sql = """
INSERT INTO ProcessData
(pid, process_name, path, memory_usage, cpu_usage)
VALUES
(%s, %s, %s, %s, %s)
"""
val = (pid, name, path, mem_usage, cpu_usage)
db_cursor.execute(sql, val)
db_connection.commit() # 提交事务
except Exception as e:
print(f"Error inserting process: {e}")
def yy():
text.delete(1.0, 'end')
text.insert('insert', '进程号 ' + '进程名 ' + ' 进程文件路径' + '\n')
for y in psutil.pids():
a = psutil.Process(y)
if a.name() == 'System Idle Process':
def yy():
text.delete(1.0,'end')
text.insert('insert','进程号 '+'进程名 '+' 进程文件路径'+'\n')
for y in psutil.pids():
a=psutil.Process(y)
if a.name()=='System Idle Process':
continue
else:
# 确保这里的缩进与'else:'对齐,通常使用四个空格
mem_info = a.memory_info()
mem_usage = mem_info.rss / 1024 # 单位转换为KB可根据需要调整
# 插入数据到数据库
insert_process(a.pid, a.name(), a.exe(), mem_usage, psutil.cpu_percent(interval=None))
text.insert('insert',str(y)+' '+a.name()+' '+a.exe()+'\n\n')
text.insert('insert', f"{y} {a.name()} {a.exe()}\n\n")
# 确保root.update()与yy()函数体对齐不在else块内
root.update()
def jc():
text.delete(1.0,'end')
mm=os.popen('tasklist')
@ -177,67 +105,6 @@ def yh():
for y in psutil.users():
text.insert('2.0',str(y.name)+' '+'运行中。。。。'+'\n')
root.update()
def end_process():
"""根据用户输入的PID结束进程"""
pid = pid_entry.get()
try:
pid = int(pid) # 将输入转换为整型
process = psutil.Process(pid)
process.terminate() # 尝试结束进程
text.insert('insert', f"尝试结束PID为{pid}的进程...\n")
root.update()
except psutil.NoSuchProcess:
text.insert('insert', f"没有找到PID为{pid}的进程。\n")
root.update()
except ValueError:
text.insert('insert', "请输入有效的数字PID。\n")
root.update()
except Exception as e:
text.insert('insert', f"结束进程时发生错误: {e}\n")
root.update()
def search_processes():
"""根据用户输入的关键词搜索进程并更新显示"""
keyword = search_entry.get().strip().lower()
if not keyword:
text.insert('insert', "请输入搜索关键词...\n")
return
found_processes = []
for proc in psutil.process_iter(['pid', 'name']):
if keyword in proc.info['name'].lower():
found_processes.append(proc.info)
if found_processes:
text.delete(1.0, 'end')
for proc_info in found_processes:
text.insert('insert', f"{proc_info['pid']} | {proc_info['name']}\n")
else:
text.insert('insert', f"未找到包含'{keyword}'的进程。\n")
root.update()
# 确保窗口大小适应新的组件
search_frame = t.Frame(root)
search_frame.pack(side='right', anchor='ne') # 定位在右侧上角
# 通过grid布局管理器可以更好地控制组件之间的对齐和间距
search_frame.columnconfigure(0, weight=1) # 让输入框所在的列自动填充空白
search_frame.rowconfigure(0, weight=1)
search_label = t.Label(search_frame, text="搜索进程:")
search_label.grid(row=0, column=0, sticky='w') # 保持左侧对齐,但不额外增加宽度
search_entry = t.Entry(search_frame)
search_entry.grid(row=0, column=1, sticky='ew') # 让输入框填充可用空间
search_entry.config(width=20) # 可选:限制输入框的初始宽度
search_button = t.Button(search_frame, text="搜索", command=search_processes)
search_button.grid(row=0, column=2, padx=(0, 5), pady=(0, 5), sticky='e') # 靠右对齐,可加微小间隔
m=t.Menu(root)
#文件菜单
file=t.Menu(m,tearoff=False)
@ -246,20 +113,6 @@ file.add_command(label='新建任务',accelerator='(N)')
file.add_command(label='退出任务栏管理器',command=root.quit,accelerator='(x)')
pid_end_frame = t.Frame(root)
pid_end_frame.pack(side=t.RIGHT, anchor=t.SE, padx=10, pady=10) # 添加padx和pady以留出空间
pid_label = t.Label(pid_end_frame, text="PID:")
pid_label.pack(side=t.LEFT)
pid_entry = t.Entry(pid_end_frame, width=5)
pid_entry.pack(side=t.LEFT, padx=(10, 0))
end_process_button = t.Button(pid_end_frame, text="结束进程", command=end_process)
end_process_button.pack(side=t.LEFT, padx=(10, 0)) # 可能需要根据实际调整padx以保持布局美观
root.geometry("400x600")
#选项菜单
ii=t.IntVar()
ii.set(1)
@ -320,7 +173,7 @@ def wlnc():
wl= float(t-f)/float(t) #为使得最后值更精确必须用float
t3.configure(text='物理内存:'+str(floor(wl*100))+'%')
root.after(2000,wlnc)
root.bind('<Visibility>',yy) #当打开窗口时显示第一个按钮选项
root.bind('<Visibility>',yy()) #当打开窗口时显示第一个按钮选项
root.bind('<Visibility>',jcs())
root.bind('<Visibility>',cpu())
root.bind('<Visibility>',wlnc())
Loading…
Cancel
Save