具有以下功能:
获取并显示显卡信息
显示 CPU 架构和核心数量
显示系统内存容量
显示磁盘使用情况和进度条
显示操作系统信息
提供刷新按钮以便重新获取信息
使用时,只需运行该 Python 脚本,程序会自动获取并显示硬件信息。注意,某些信息(如 GPU 型号)的获取可能需要安装额外的库(如 GPUtil),你可以使用pip install GPUtil来安装它。
基于 Python 的硬件信息获取程序,它可以获取显卡、CPU、内存和存储等硬件信息。这个程序使用了 tkinter 创建图形界面
安装缺失的模块:
安装GPUtil模块,
具体操作如下:
打开命令提示符或者终端
输入命令:
pip install GPUtil
等待安装完成之后,再次运行程序
源码如下一
import tkinter as tk
from tkinter import ttk
import platform
import psutil
import os
import subprocess
import sys
import ctypes
class HardwareInfoApp:
def __init__(self, root):
self.root = root
self.root.title("硬件信息查看器")
self.root.geometry("500x400")
self.root.resizable(True, True)
# 设置中文字体支持
self.style = ttk.Style()
self.style.configure("TLabel", font=("SimHei", 10))
self.style.configure("TButton", font=("SimHei", 10))
self.create_widgets()
def create_widgets(self):
# 创建主框架
main_frame = ttk.Frame(self.root, padding="20")
main_frame.pack(fill=tk.BOTH, expand=True)
# 标题
title_label = ttk.Label(main_frame, text="系统硬件信息", font=("SimHei", 16, "bold"))
title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20), sticky=tk.W)
# GPU信息
ttk.Label(main_frame, text="显卡:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.gpu_info = ttk.Label(main_frame, text="检测中...")
self.gpu_info.grid(row=1, column=1, sticky=tk.W, pady=5)
# CPU信息
ttk.Label(main_frame, text="CPU架构:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.cpu_model = ttk.Label(main_frame, text="检测中...")
self.cpu_model.grid(row=2, column=1, sticky=tk.W, pady=5)
ttk.Label(main_frame, text="CPU核心:").grid(row=3, column=0, sticky=tk.W, pady=5)
self.cpu_cores = ttk.Label(main_frame, text="检测中...")
self.cpu_cores.grid(row=3, column=1, sticky=tk.W, pady=5)
# 内存信息
ttk.Label(main_frame, text="内存容量:").grid(row=4, column=0, sticky=tk.W, pady=5)
self.memory_capacity = ttk.Label(main_frame, text="检测中...")
self.memory_capacity.grid(row=4, column=1, sticky=tk.W, pady=5)
# 存储信息
ttk.Label(main_frame, text="磁盘使用:").grid(row=5, column=0, sticky=tk.W, pady=5)
self.storage_info = ttk.Label(main_frame, text="检测中...")
self.storage_info.grid(row=5, column=1, sticky=tk.W, pady=5)
# 创建进度条
self.storage_progress = ttk.Progressbar(main_frame, orient="horizontal", length=300, mode="determinate")
self.storage_progress.grid(row=6, column=1, sticky=tk.W, pady=5)
# 平台信息
ttk.Label(main_frame, text="操作系统:").grid(row=7, column=0, sticky=tk.W, pady=5)
self.platform_info = ttk.Label(main_frame, text="检测中...")
self.platform_info.grid(row=7, column=1, sticky=tk.W, pady=5)
# 刷新按钮
refresh_button = ttk.Button(main_frame, text="刷新信息", command=self.get_hardware_info)
refresh_button.grid(row=8, column=0, columnspan=2, pady=20)
# 状态栏
self.status_var = tk.StringVar()
self.status_var.set("准备就绪")
status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
status_bar.pack(side=tk.BOTTOM, fill=tk.X)
# 自动获取硬件信息
self.get_hardware_info()
def get_hardware_info(self):
"""获取并显示硬件信息"""
try:
self.status_var.set("正在获取硬件信息...")
self.root.update()
# 获取GPU信息
try:
# 尝试导入GPUtil
try:
import GPUtil
gpus = GPUtil.getGPUs()
if gpus:
gpu_info = gpus[0].name
else:
gpu_info = "集成显卡"
except ImportError:
# 如果没有GPUtil模块,则使用替代方法
if platform.system() == "Windows":
try:
# 使用dxdiag命令获取显卡信息
result = subprocess.check_output("dxdiag /t dxdiag.txt", shell=True, timeout=10)
with open("dxdiag.txt", "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
start = content.find("Card name:") + 10
end = content.find("\n", start)
gpu_info = content[start:end].strip()
os.remove("dxdiag.txt")
except:
gpu_info = "集成显卡"
elif platform.system() == "Linux":
try:
# 在Linux上尝试使用lspci命令
result = subprocess.check_output("lspci | grep VGA", shell=True, text=True)
gpu_info = result.strip() if result else "集成显卡"
except:
gpu_info = "集成显卡"
elif platform.system() == "Darwin": # macOS
try:
# 在macOS上尝试使用system_profiler命令
result = subprocess.check_output("system_profiler SPDisplaysDataType", shell=True, text=True)
lines = result.split('\n')
gpu_info = "集成显卡"
for line in lines:
if "Chipset Model:" in line:
gpu_info = line.split(":")[1].strip()
break
except:
gpu_info = "集成显卡"
else:
gpu_info = "集成显卡"
except Exception as e:
gpu_info = "检测失败"
# 获取CPU信息
cpu_arch = platform.machine()
if platform.system() == "Windows":
if "64" in platform.architecture()[0]:
cpu_arch = "x64 (64位)"
else:
cpu_arch = "x86 (32位)"
elif platform.system() == "Darwin": # macOS
if "ARM" in platform.processor() or "arm" in platform.processor():
cpu_arch = "Apple Silicon"
else:
cpu_arch = "Intel x64"
elif platform.system() == "Linux":
if "aarch64" in platform.machine():
cpu_arch = "ARM64 架构"
elif "arm" in platform.machine():
cpu_arch = "ARM 架构"
cpu_cores = f"{psutil.cpu_count(logical=True)} 个逻辑核心"
# 获取内存信息
total_memory = psutil.virtual_memory().total / (1024 ** 3) # GB
memory_capacity = f"{total_memory:.1f} GB"
# 获取存储信息
try:
# 导入缺失的shutil模块
import shutil
total, used, free = shutil.disk_usage("/")
total_gb = total / (1024 ** 3)
used_gb = used / (1024 ** 3)
usage_percent = (used / total) * 100
storage_info = f"磁盘使用: {used_gb:.2f}GB / {total_gb:.1f}GB"
storage_percent = f"{usage_percent:.0f}%"
except Exception as e:
storage_info = "存储信息不可用"
storage_percent = "0%"
# 获取平台信息
platform_info = platform.platform()
# 更新UI
self.gpu_info.config(text=gpu_info)
self.cpu_model.config(text=cpu_arch)
self.cpu_cores.config(text=cpu_cores)
self.memory_capacity.config(text=memory_capacity)
self.storage_info.config(text=storage_info)
self.storage_progress["value"] = float(storage_percent.strip("%"))
self.platform_info.config(text=platform_info)
self.status_var.set("硬件信息已更新")
except Exception as e:
self.status_var.set(f"获取硬件信息时出错: {str(e)}")
# 设置默认值
self.gpu_info.config(text="检测失败")
self.cpu_model.config(text="检测失败")
self.cpu_cores.config(text="检测失败")
self.memory_capacity.config(text="检测失败")
self.storage_info.config(text="检测失败")
self.platform_info.config(text="检测失败")
if __name__ == "__main__":
# 确保中文显示正常
if platform.system() == "Windows":
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(2)
root = tk.Tk()
app = HardwareInfoApp(root)
root.mainloop()
功能完整的硬件信息查看器
支持多平台(Windows、macOS、Linux)
提供丰富的硬件信息,包括 CPU、内存、磁盘、网络等
实时监控系统性能,包括 CPU 使用率、内存使用率、磁盘使用率等
提供进程监控功能,可以查看和管理系统进程
界面美观,支持中文显示
使用前需要安装以下依赖:
plaintext
pip install psutil GPUtil
这个应用程序提供了一个友好的图形界面
源码如下二
import tkinter as tk
from tkinter import ttk
import platform
import psutil
import os
import subprocess
import sys
import ctypes
import time
import socket
import threading
import re
import GPUtil # 如果有GPU监控需求
class HardwareInfoApp:
def __init__(self, root):
self.root = root
self.root.title("硬件信息查看器")
self.root.geometry("1000x800") # 增加窗口尺寸
self.root.resizable(True, True)
# 设置中文字体支持
self.style = ttk.Style()
self.style.configure("TLabel", font=("SimHei", 10))
self.style.configure("TButton", font=("SimHei", 10))
self.style.configure("TNotebook", font=("SimHei", 10))
self.create_widgets()
def create_widgets(self):
# 创建主框架
main_frame = ttk.Frame(self.root, padding="10")
main_frame.pack(fill=tk.BOTH, expand=True)
# 创建选项卡控件
self.notebook = ttk.Notebook(main_frame)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# 基本信息选项卡
self.basic_tab = ttk.Frame(self.notebook)
self.notebook.add(self.basic_tab, text="基本信息")
# 高级信息选项卡
self.advanced_tab = ttk.Frame(self.notebook)
self.notebook.add(self.advanced_tab, text="高级信息")
# 网络信息选项卡
self.network_tab = ttk.Frame(self.notebook)
self.notebook.add(self.network_tab, text="网络信息")
# 性能监控选项卡
self.performance_tab = ttk.Frame(self.notebook)
self.notebook.add(self.performance_tab, text="性能监控")
# 进程监控选项卡
self.process_tab = ttk.Frame(self.notebook)
self.notebook.add(self.process_tab, text="进程监控")
# 创建各选项卡内容
self.create_basic_tab()
self.create_advanced_tab()
self.create_network_tab()
self.create_performance_tab()
self.create_process_tab() # 新增进程监控选项卡
# 状态栏
self.status_var = tk.StringVar()
self.status_var.set("准备就绪")
status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
status_bar.pack(side=tk.BOTTOM, fill=tk.X)
# 自动获取硬件信息
self.get_hardware_info()
# 开始性能监控
self.is_monitoring = True
self.start_performance_monitoring()
def create_basic_tab(self):
# 创建基本信息框架
frame = ttk.LabelFrame(self.basic_tab, text="系统硬件信息", padding="10")
frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# 标题
title_label = ttk.Label(frame, text="硬件信息摘要", font=("SimHei", 14, "bold"))
title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20), sticky=tk.W)
# 显卡信息
ttk.Label(frame, text="显卡:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.gpu_info = ttk.Label(frame, text="检测中...")
self.gpu_info.grid(row=1, column=1, sticky=tk.W, pady=5)
# GPU温度
ttk.Label(frame, text="GPU温度:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.gpu_temp = ttk.Label(frame, text="检测中...")
self.gpu_temp.grid(row=2, column=1, sticky=tk.W, pady=5)
# CPU信息
ttk.Label(frame, text="CPU架构:").grid(row=3, column=0, sticky=tk.W, pady=5)
self.cpu_model = ttk.Label(frame, text="检测中...")
self.cpu_model.grid(row=3, column=1, sticky=tk.W, pady=5)
ttk.Label(frame, text="CPU核心:").grid(row=4, column=0, sticky=tk.W, pady=5)
self.cpu_cores = ttk.Label(frame, text="检测中...")
self.cpu_cores.grid(row=4, column=1, sticky=tk.W, pady=5)
# CPU温度
ttk.Label(frame, text="CPU温度:").grid(row=5, column=0, sticky=tk.W, pady=5)
self.cpu_temp = ttk.Label(frame, text="检测中...")
self.cpu_temp.grid(row=5, column=1, sticky=tk.W, pady=5)
# 内存信息
ttk.Label(frame, text="内存容量:").grid(row=6, column=0, sticky=tk.W, pady=5)
self.memory_capacity = ttk.Label(frame, text="检测中...")
self.memory_capacity.grid(row=6, column=1, sticky=tk.W, pady=5)
# 内存使用情况
ttk.Label(frame, text="内存使用:").grid(row=7, column=0, sticky=tk.W, pady=5)
self.memory_usage = ttk.Label(frame, text="检测中...")
self.memory_usage.grid(row=7, column=1, sticky=tk.W, pady=5)
# 存储信息
ttk.Label(frame, text="磁盘使用:").grid(row=8, column=0, sticky=tk.W, pady=5)
self.storage_info = ttk.Label(frame, text="检测中...")
self.storage_info.grid(row=8, column=1, sticky=tk.W, pady=5)
# 创建进度条
self.storage_progress = ttk.Progressbar(frame, orient="horizontal", length=300, mode="determinate")
self.storage_progress.grid(row=9, column=1, sticky=tk.W, pady=5)
# 平台信息
ttk.Label(frame, text="操作系统:").grid(row=10, column=0, sticky=tk.W, pady=5)
self.platform_info = ttk.Label(frame, text="检测中...")
self.platform_info.grid(row=10, column=1, sticky=tk.W, pady=5)
# 刷新按钮
refresh_button = ttk.Button(frame, text="刷新信息", command=self.get_hardware_info)
refresh_button.grid(row=11, column=0, columnspan=2, pady=20)
def create_advanced_tab(self):
# 创建高级信息框架
frame = ttk.LabelFrame(self.advanced_tab, text="高级硬件信息", padding="10")
frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# 网络信息
network_frame = ttk.LabelFrame(frame, text="网络基础信息", padding="10")
network_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=10)
ttk.Label(network_frame, text="主机名:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.hostname = ttk.Label(network_frame, text="检测中...")
self.hostname.grid(row=0, column=1, sticky=tk.W, pady=5)
ttk.Label(network_frame, text="本地IP:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.local_ip = ttk.Label(network_frame, text="检测中...")
self.local_ip.grid(row=1, column=1, sticky=tk.W, pady=5)
ttk.Label(network_frame, text="公网IP:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.public_ip = ttk.Label(network_frame, text="检测中...")
self.public_ip.grid(row=2, column=1, sticky=tk.W, pady=5)
# 电池信息
battery_frame = ttk.LabelFrame(frame, text="电池信息", padding="10")
battery_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=10)
ttk.Label(battery_frame, text="电池状态:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.battery_status = ttk.Label(battery_frame, text="检测中...")
self.battery_status.grid(row=0, column=1, sticky=tk.W, pady=5)
ttk.Label(battery_frame, text="电池电量:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.battery_percent = ttk.Label(battery_frame, text="检测中...")
self.battery_percent.grid(row=1, column=1, sticky=tk.W, pady=5)
self.battery_progress = ttk.Progressbar(battery_frame, orient="horizontal", length=300, mode="determinate")
self.battery_progress.grid(row=2, column=0, columnspan=2, sticky=tk.W, pady=5)
# 温度信息
temp_frame = ttk.LabelFrame(frame, text="温度信息", padding="10")
temp_frame.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=10)
ttk.Label(temp_frame, text="CPU温度:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.cpu_temp_detail = ttk.Label(temp_frame, text="检测中...")
self.cpu_temp_detail.grid(row=0, column=1, sticky=tk.W, pady=5)
ttk.Label(temp_frame, text="GPU温度:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.gpu_temp_detail = ttk.Label(temp_frame, text="检测中...")
self.gpu_temp_detail.grid(row=1, column=1, sticky=tk.W, pady=5)
ttk.Label(temp_frame, text="硬盘温度:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.disk_temp = ttk.Label(temp_frame, text="检测中...")
self.disk_temp.grid(row=2, column=1, sticky=tk.W, pady=5)
# 传感器信息
sensors_frame = ttk.LabelFrame(frame, text="传感器信息", padding="10")
sensors_frame.grid(row=0, column=1, rowspan=3, sticky=(tk.N, tk.S, tk.W, tk.E), pady=10)
self.sensors_text = tk.Text(sensors_frame, height=10, width=30)
self.sensors_text.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
scrollbar = ttk.Scrollbar(sensors_frame, command=self.sensors_text.yview)
scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
self.sensors_text.config(yscrollcommand=scrollbar.set)
# 设置网格权重
frame.grid_columnconfigure(1, weight=1)
frame.grid_rowconfigure(2, weight=1)
def create_network_tab(self):
"""创建网络信息选项卡"""
# 创建网络信息框架
frame = ttk.LabelFrame(self.network_tab, text="网络连接详情", padding="10")
frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# 网络接口列表
interface_frame = ttk.LabelFrame(frame, text="网络接口", padding="10")
interface_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
# 创建接口列表的Treeview
columns = ("interface", "status", "ip", "mac", "speed")
self.interface_tree = ttk.Treeview(interface_frame, columns=columns, show="headings")
self.interface_tree.heading("interface", text="接口名称")
self.interface_tree.heading("status", text="状态")
self.interface_tree.heading("ip", text="IP地址")
self.interface_tree.heading("mac", text="MAC地址")
self.interface_tree.heading("speed", text="速度(Mbps)")
self.interface_tree.column("interface", width=120)
self.interface_tree.column("status", width=80)
self.interface_tree.column("ip", width=150)
self.interface_tree.column("mac", width=150)
self.interface_tree.column("speed", width=100)
self.interface_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# 添加滚动条
scrollbar = ttk.Scrollbar(interface_frame, orient="vertical", command=self.interface_tree.yview)
self.interface_tree.configure(yscroll=scrollbar.set)
scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
# 网络统计信息
stats_frame = ttk.LabelFrame(frame, text="网络统计", padding="10")
stats_frame.grid(row=0, column=1, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
ttk.Label(stats_frame, text="总上传量:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.total_upload = ttk.Label(stats_frame, text="0 MB")
self.total_upload.grid(row=0, column=1, sticky=tk.W, pady=5)
ttk.Label(stats_frame, text="总下载量:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.total_download = ttk.Label(stats_frame, text="0 MB")
self.total_download.grid(row=1, column=1, sticky=tk.W, pady=5)
ttk.Label(stats_frame, text="当前上传速度:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.current_upload = ttk.Label(stats_frame, text="0 KB/s")
self.current_upload.grid(row=2, column=1, sticky=tk.W, pady=5)
ttk.Label(stats_frame, text="当前下载速度:").grid(row=3, column=0, sticky=tk.W, pady=5)
self.current_download = ttk.Label(stats_frame, text="0 KB/s")
self.current_download.grid(row=3, column=1, sticky=tk.W, pady=5)
ttk.Label(stats_frame, text="网络连接数:").grid(row=4, column=0, sticky=tk.W, pady=5)
self.connection_count = ttk.Label(stats_frame, text="0")
self.connection_count.grid(row=4, column=1, sticky=tk.W, pady=5)
# 活动连接
connections_frame = ttk.LabelFrame(frame, text="活动网络连接", padding="10")
connections_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
# 创建连接列表的Treeview
conn_columns = ("local_addr", "remote_addr", "status", "pid", "process", "traffic")
self.connection_tree = ttk.Treeview(connections_frame, columns=conn_columns, show="headings")
self.connection_tree.heading("local_addr", text="本地地址")
self.connection_tree.heading("remote_addr", text="远程地址")
self.connection_tree.heading("status", text="状态")
self.connection_tree.heading("pid", text="PID")
self.connection_tree.heading("process", text="进程")
self.connection_tree.heading("traffic", text="流量")
self.connection_tree.column("local_addr", width=150)
self.connection_tree.column("remote_addr", width=150)
self.connection_tree.column("status", width=80)
self.connection_tree.column("pid", width=60)
self.connection_tree.column("process", width=150)
self.connection_tree.column("traffic", width=100)
self.connection_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# 添加滚动条
conn_scrollbar = ttk.Scrollbar(connections_frame, orient="vertical", command=self.connection_tree.yview)
self.connection_tree.configure(yscroll=conn_scrollbar.set)
conn_scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
# 设置网格权重
frame.grid_columnconfigure(0, weight=1)
frame.grid_columnconfigure(1, weight=1)
frame.grid_rowconfigure(1, weight=1)
def create_performance_tab(self):
# 创建性能监控框架
frame = ttk.LabelFrame(self.performance_tab, text="系统性能监控", padding="10")
frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# CPU使用率
cpu_frame = ttk.LabelFrame(frame, text="CPU使用率", padding="10")
cpu_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
self.cpu_usage_label = ttk.Label(cpu_frame, text="0%")
self.cpu_usage_label.grid(row=0, column=0, sticky=tk.W, pady=5)
self.cpu_usage_progress = ttk.Progressbar(cpu_frame, orient="horizontal", length=300, mode="determinate")
self.cpu_usage_progress.grid(row=1, column=0, sticky=tk.W, pady=5)
# 内存使用率
memory_frame = ttk.LabelFrame(frame, text="内存使用率", padding="10")
memory_frame.grid(row=0, column=1, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
self.memory_usage_label = ttk.Label(memory_frame, text="0%")
self.memory_usage_label.grid(row=0, column=0, sticky=tk.W, pady=5)
self.memory_usage_progress = ttk.Progressbar(memory_frame, orient="horizontal", length=300, mode="determinate")
self.memory_usage_progress.grid(row=1, column=0, sticky=tk.W, pady=5)
# 磁盘使用率
disk_frame = ttk.LabelFrame(frame, text="磁盘使用率", padding="10")
disk_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
self.disk_usage_label = ttk.Label(disk_frame, text="0%")
self.disk_usage_label.grid(row=0, column=0, sticky=tk.W, pady=5)
self.disk_usage_progress = ttk.Progressbar(disk_frame, orient="horizontal", length=300, mode="determinate")
self.disk_usage_progress.grid(row=1, column=0, sticky=tk.W, pady=5)
# 网络使用
network_frame = ttk.LabelFrame(frame, text="网络使用", padding="10")
network_frame.grid(row=1, column=1, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
ttk.Label(network_frame, text="上传:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.upload_speed = ttk.Label(network_frame, text="0 KB/s")
self.upload_speed.grid(row=0, column=1, sticky=tk.W, pady=5)
ttk.Label(network_frame, text="下载:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.download_speed = ttk.Label(network_frame, text="0 KB/s")
self.download_speed.grid(row=1, column=1, sticky=tk.W, pady=5)
# CPU核心使用率
self.cpu_cores_frame = ttk.LabelFrame(frame, text="CPU核心使用率", padding="10")
self.cpu_cores_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
self.cpu_cores_progress = []
self.cpu_cores_labels = []
# 初始化CPU核心监控UI
core_count = psutil.cpu_count(logical=True)
cols = 4 # 每行显示4个核心
for i in range(core_count):
row = i // cols
col = i % cols
label = ttk.Label(self.cpu_cores_frame, text=f"核心 {i}: 0%")
label.grid(row=row, column=col*2, sticky=tk.W, pady=5)
self.cpu_cores_labels.append(label)
progress = ttk.Progressbar(self.cpu_cores_frame, orient="horizontal", length=180, mode="determinate")
progress.grid(row=row, column=col*2+1, sticky=tk.W, pady=5)
self.cpu_cores_progress.append(progress)
# 设置网格权重
frame.grid_columnconfigure(0, weight=1)
frame.grid_columnconfigure(1, weight=1)
frame.grid_rowconfigure(2, weight=1)
def create_process_tab(self):
"""创建进程监控选项卡"""
# 创建进程监控框架
frame = ttk.LabelFrame(self.process_tab, text="进程监控", padding="10")
frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# 进程过滤和排序
filter_frame = ttk.Frame(frame)
filter_frame.pack(fill=tk.X, padx=5, pady=5)
ttk.Label(filter_frame, text="过滤:").pack(side=tk.LEFT, padx=5)
self.filter_var = tk.StringVar()
self.filter_entry = ttk.Entry(filter_frame, textvariable=self.filter_var, width=30)
self.filter_entry.pack(side=tk.LEFT, padx=5)
self.filter_entry.bind("<KeyRelease>", self.filter_processes)
ttk.Label(filter_frame, text="排序:").pack(side=tk.LEFT, padx=5)
self.sort_var = tk.StringVar(value="cpu")
ttk.Radiobutton(filter_frame, text="CPU", variable=self.sort_var, value="cpu", command=self.refresh_processes).pack(side=tk.LEFT)
ttk.Radiobutton(filter_frame, text="内存", variable=self.sort_var, value="memory", command=self.refresh_processes).pack(side=tk.LEFT)
# 进程列表
columns = ("pid", "name", "cpu", "memory", "status", "username", "threads")
self.process_tree = ttk.Treeview(frame, columns=columns, show="headings")
self.process_tree.heading("pid", text="PID")
self.process_tree.heading("name", text="进程名称")
self.process_tree.heading("cpu", text="CPU(%)")
self.process_tree.heading("memory", text="内存(MB)")
self.process_tree.heading("status", text="状态")
self.process_tree.heading("username", text="用户")
self.process_tree.heading("threads", text="线程")
self.process_tree.column("pid", width=80)
self.process_tree.column("name", width=200)
self.process_tree.column("cpu", width=80, anchor=tk.E)
self.process_tree.column("memory", width=100, anchor=tk.E)
self.process_tree.column("status", width=100)
self.process_tree.column("username", width=120)
self.process_tree.column("threads", width=80, anchor=tk.E)
self.process_tree.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# 添加滚动条
scrollbar = ttk.Scrollbar(frame, orient="vertical", command=self.process_tree.yview)
self.process_tree.configure(yscroll=scrollbar.set)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 进程操作按钮
button_frame = ttk.Frame(frame)
button_frame.pack(fill=tk.X, padx=5, pady=5)
self.kill_button = ttk.Button(button_frame, text="终止进程", command=self.kill_process)
self.kill_button.pack(side=tk.LEFT, padx=5)
self.refresh_button = ttk.Button(button_frame, text="刷新列表", command=self.refresh_processes)
self.refresh_button.pack(side=tk.LEFT, padx=5)
# 进程详情
self.detail_frame = ttk.LabelFrame(frame, text="进程详情", padding="10")
self.detail_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.detail_text = tk.Text(self.detail_frame, height=5, width=30)
self.detail_text.pack(fill=tk.BOTH, expand=True)
# 绑定选择事件
self.process_tree.bind("<<TreeviewSelect>>", self.show_process_details)
def get_hardware_info(self):
"""获取并显示硬件信息"""
try:
self.status_var.set("正在获取硬件信息...")
self.root.update()
# 获取GPU信息
try:
gpu_info = "集成显卡"
gpu_temp = "N/A"
# 尝试使用GPUtil获取GPU信息
try:
gpus = GPUtil.getGPUs()
if gpus:
gpu = gpus[0]
gpu_info = gpu.name
gpu_temp = f"{gpu.temperature}°C"
except:
# 如果没有GPUtil模块或获取失败,则使用替代方法
if platform.system() == "Windows":
try:
# 使用dxdiag命令获取显卡信息
result = subprocess.check_output("dxdiag /t dxdiag.txt", shell=True, timeout=10)
with open("dxdiag.txt", "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
start = content.find("Card name:") + 10
end = content.find("\n", start)
gpu_info = content[start:end].strip()
os.remove("dxdiag.txt")
except:
pass
except Exception as e:
gpu_info = "检测失败"
gpu_temp = "N/A"
# 获取CPU信息
cpu_arch = platform.machine()
if platform.system() == "Windows":
if "64" in platform.architecture()[0]:
cpu_arch = "x64 (64位)"
else:
cpu_arch = "x86 (32位)"
elif platform.system() == "Darwin": # macOS
if "ARM" in platform.processor() or "arm" in platform.processor():
cpu_arch = "Apple Silicon"
else:
cpu_arch = "Intel x64"
elif platform.system() == "Linux":
if "aarch64" in platform.machine():
cpu_arch = "ARM64 架构"
elif "arm" in platform.machine():
cpu_arch = "ARM 架构"
cpu_cores = f"{psutil.cpu_count(logical=True)} 个逻辑核心"
# 获取CPU温度
cpu_temp = "N/A"
cpu_temp_detail = "N/A"
try:
if hasattr(psutil, 'sensors_temperatures'):
temps = psutil.sensors_temperatures()
if temps:
if 'coretemp' in temps:
cores = temps['coretemp']
if cores:
cpu_temp = f"{cores[0].current}°C"
cpu_temp_detail = ", ".join([f"{core.label}: {core.current}°C" for core in cores])
elif 'cpu-thermal' in temps: # macOS
cores = temps['cpu-thermal']
if cores:
cpu_temp = f"{cores[0].current}°C"
cpu_temp_detail = ", ".join([f"{core.label}: {core.current}°C" for core in cores])
except:
pass
# 获取内存信息
memory = psutil.virtual_memory()
total_memory = memory.total / (1024 ** 3) # GB
used_memory = memory.used / (1024 ** 3) # GB
memory_percent = memory.percent
memory_capacity = f"{total_memory:.1f} GB"
memory_usage = f"{used_memory:.1f} GB / {total_memory:.1f} GB ({memory_percent}%)"
# 获取存储信息
try:
import shutil
total, used, free = shutil.disk_usage("/")
total_gb = total / (1024 ** 3)
used_gb = used / (1024 ** 3)
usage_percent = (used / total) * 100
storage_info = f"磁盘使用: {used_gb:.2f}GB / {total_gb:.1f}GB"
storage_percent = f"{usage_percent:.0f}%"
except Exception as e:
storage_info = "存储信息不可用"
storage_percent = "0%"
# 获取平台信息
platform_info = platform.platform()
# 更新基本信息
self.gpu_info.config(text=gpu_info)
self.gpu_temp.config(text=gpu_temp)
self.cpu_model.config(text=cpu_arch)
self.cpu_cores.config(text=cpu_cores)
self.cpu_temp.config(text=cpu_temp)
self.memory_capacity.config(text=memory_capacity)
self.memory_usage.config(text=memory_usage)
self.storage_info.config(text=storage_info)
self.storage_progress["value"] = float(storage_percent.strip("%"))
self.platform_info.config(text=platform_info)
# 获取高级信息
self.get_advanced_info()
# 获取网络信息
self.get_network_info()
# 刷新进程列表
self.refresh_processes()
self.status_var.set("硬件信息已更新")
except Exception as e:
self.status_var.set(f"获取硬件信息时出错: {str(e)}")
# 设置默认值
self.gpu_info.config(text="检测失败")
self.gpu_temp.config(text="N/A")
self.cpu_model.config(text="检测失败")
self.cpu_cores.config(text="检测失败")
self.cpu_temp.config(text="N/A")
self.memory_capacity.config(text="检测失败")
self.memory_usage.config(text="检测失败")
self.storage_info.config(text="检测失败")
self.storage_progress["value"] = 0
self.platform_info.config(text="检测失败")
def get_advanced_info(self):
"""获取并显示高级硬件信息"""
try:
# 获取网络信息
hostname = socket.gethostname()
try:
local_ip = socket.gethostbyname(hostname)
except:
local_ip = "无法获取"
# 获取公网IP(异步)
threading.Thread(target=self.get_public_ip).start()
# 更新网络信息
self.hostname.config(text=hostname)
self.local_ip.config(text=local_ip)
# 获取电池信息
try:
battery = psutil.sensors_battery()
if battery:
percent = battery.percent
power_plugged = battery.power_plugged
status = "充电中" if power_plugged else "放电中"
if percent >= 95 and power_plugged:
status = "已充满"
self.battery_status.config(text=status)
self.battery_percent.config(text=f"{percent}%")
self.battery_progress["value"] = percent
else:
self.battery_status.config(text="未检测到电池")
self.battery_percent.config(text="N/A")
self.battery_progress["value"] = 0
except:
self.battery_status.config(text="无法获取电池信息")
self.battery_percent.config(text="N/A")
self.battery_progress["value"] = 0
# 获取温度信息
try:
cpu_temp = "N/A"
gpu_temp = "N/A"
disk_temp = "N/A"
if hasattr(psutil, 'sensors_temperatures'):
temps = psutil.sensors_temperatures()
if temps:
if 'coretemp' in temps:
cores = temps['coretemp']
if cores:
cpu_temp = ", ".join([f"{core.label}: {core.current}°C" for core in cores])
elif 'cpu-thermal' in temps: # macOS
cores = temps['cpu-thermal']
if cores:
cpu_temp = ", ".join([f"{core.label}: {core.current}°C" for core in cores])
# 尝试获取GPU温度
try:
gpus = GPUtil.getGPUs()
if gpus:
gpu_temp = f"{gpus[0].temperature}°C"
except:
pass
# 尝试获取磁盘温度(这在大多数系统上可能不可用)
try:
if platform.system() == "Linux":
# 在Linux上尝试使用smartctl命令
try:
result = subprocess.check_output("smartctl -A /dev/sda | grep Temperature_Celsius", shell=True, text=True)
if result:
parts = result.strip().split()
if len(parts) > 9:
disk_temp = f"{parts[9]}°C"
except:
pass
except:
pass
self.cpu_temp_detail.config(text=cpu_temp)
self.gpu_temp_detail.config(text=gpu_temp)
self.disk_temp.config(text=disk_temp)
except:
self.cpu_temp_detail.config(text="检测失败")
self.gpu_temp_detail.config(text="检测失败")
self.disk_temp.config(text="检测失败")
# 获取传感器信息
try:
self.sensors_text.delete(1.0, tk.END)
if hasattr(psutil, 'sensors_temperatures'):
temps = psutil.sensors_temperatures()
if temps:
self.sensors_text.insert(tk.END, "温度传感器:\n")
for name, entries in temps.items():
self.sensors_text.insert(tk.END, f" {name}:\n")
for entry in entries:
self.sensors_text.insert(tk.END, f" {entry.label}: {entry.current}°C\n")
if hasattr(psutil, 'sensors_fans'):
fans = psutil.sensors_fans()
if fans:
self.sensors_text.insert(tk.END, "\n风扇转速:\n")
for name, entries in fans.items():
self.sensors_text.insert(tk.END, f" {name}:\n")
for entry in entries:
self.sensors_text.insert(tk.END, f" {entry.label}: {entry.current} RPM\n")
if hasattr(psutil, 'sensors_battery'):
battery = psutil.sensors_battery()
if battery:
self.sensors_text.insert(tk.END, "\n电池状态:\n")
self.sensors_text.insert(tk.END, f" 电量: {battery.percent}%\n")
self.sensors_text.insert(tk.END, f" 状态: {'充电中' if battery.power_plugged else '放电中'}\n")
except:
self.sensors_text.delete(1.0, tk.END)
self.sensors_text.insert(tk.END, "无法获取传感器信息")
except Exception as e:
self.status_var.set(f"获取高级信息时出错: {str(e)}")
def get_public_ip(self):
"""异步获取公网IP"""
try:
import requests
response = requests.get('https://api.ipify.org', timeout=5)
public_ip = response.text
self.public_ip.config(text=public_ip)
except:
self.public_ip.config(text="无法获取")
def get_network_info(self):
"""获取并显示网络信息"""
try:
# 清除现有接口信息
for item in self.interface_tree.get_children():
self.interface_tree.delete(item)
# 获取网络接口信息
interfaces = psutil.net_if_addrs()
stats = psutil.net_if_stats()
for interface, addresses in interfaces.items():
status = "活跃" if interface in stats and stats[interface].isup else "非活跃"
ip = "N/A"
mac = "N/A"
speed = "N/A"
for addr in addresses:
if addr.family == socket.AF_INET:
ip = addr.address
elif addr.family == psutil.AF_LINK:
mac = addr.address
# 尝试获取接口速度
try:
if interface in stats:
speed = stats[interface].speed
if speed:
speed = str(speed)
except:
pass
self.interface_tree.insert("", "end", values=(interface, status, ip, mac, speed))
# 获取网络统计信息
net_io = psutil.net_io_counters()
self.total_upload.config(text=f"{net_io.bytes_sent / (1024**2):.2f} MB")
self.total_download.config(text=f"{net_io.bytes_recv / (1024**2):.2f} MB")
# 计算当前网络速度
if not hasattr(self, 'prev_net_io'):
self.prev_net_io = net_io
self.current_upload.config(text="0 KB/s")
self.current_download.config(text="0 KB/s")
else:
upload_speed = (net_io.bytes_sent - self.prev_net_io.bytes_sent) / 1024
download_speed = (net_io.bytes_recv - self.prev_net_io.bytes_recv) / 1024
self.current_upload.config(text=f"{upload_speed:.2f} KB/s")
self.current_download.config(text=f"{download_speed:.2f} KB/s")
self.prev_net_io = net_io
# 清除现有连接信息
for item in self.connection_tree.get_children():
self.connection_tree.delete(item)
# 获取网络连接信息
connections = psutil.net_connections(kind='inet')
self.connection_count.config(text=str(len(connections)))
# 只显示前50个连接以避免性能问题
for conn in connections[:50]:
local_addr = f"{conn.laddr[0]}:{conn.laddr[1]}" if conn.laddr else "N/A"
remote_addr = f"{conn.raddr[0]}:{conn.raddr[1]}" if conn.raddr else "N/A"
status = conn.status
pid = conn.pid or "N/A"
process_name = "N/A"
traffic = "N/A"
if conn.pid:
try:
process = psutil.Process(conn.pid)
process_name = process.name()
# 这里无法准确获取单个连接的流量,仅作示例
traffic = "N/A"
except:
pass
self.connection_tree.insert("", "end", values=(local_addr, remote_addr, status, pid, process_name, traffic))
except Exception as e:
self.status_var.set(f"获取网络信息时出错: {str(e)}")
def start_performance_monitoring(self):
"""开始性能监控"""
if not self.is_monitoring:
return
try:
# 获取CPU使用率
cpu_percent = psutil.cpu_percent(interval=1)
self.cpu_usage_label.config(text=f"{cpu_percent}%")
self.cpu_usage_progress["value"] = cpu_percent
# 获取每个CPU核心的使用率
cpu_cores_percent = psutil.cpu_percent(percpu=True)
for i, percent in enumerate(cpu_cores_percent):
if i < len(self.cpu_cores_labels) and i < len(self.cpu_cores_progress):
self.cpu_cores_labels[i].config(text=f"核心 {i}: {percent}%")
self.cpu_cores_progress[i]["value"] = percent
# 获取内存使用率
memory = psutil.virtual_memory()
memory_percent = memory.percent
self.memory_usage_label.config(text=f"{memory_percent}%")
self.memory_usage_progress["value"] = memory_percent
# 获取磁盘使用率
try:
import shutil
total, used, free = shutil.disk_usage("/")
disk_percent = (used / total) * 100
self.disk_usage_label.config(text=f"{disk_percent:.1f}%")
self.disk_usage_progress["value"] = disk_percent
except:
self.disk_usage_label.config(text="N/A")
self.disk_usage_progress["value"] = 0
# 获取网络使用
net_io_counters = psutil.net_io_counters()
if not hasattr(self, 'prev_bytes_sent'):
self.prev_bytes_sent = net_io_counters.bytes_sent
self.prev_bytes_recv = net_io_counters.bytes_recv
else:
upload_speed = (net_io_counters.bytes_sent - self.prev_bytes_sent) / 1024
download_speed = (net_io_counters.bytes_recv - self.prev_bytes_recv) / 1024
self.upload_speed.config(text=f"{upload_speed:.2f} KB/s")
self.download_speed.config(text=f"{download_speed:.2f} KB/s")
self.prev_bytes_sent = net_io_counters.bytes_sent
self.prev_bytes_recv = net_io_counters.bytes_recv
# 每2秒更新一次
self.root.after(2000, self.start_performance_monitoring)
except Exception as e:
self.status_var.set(f"性能监控出错: {str(e)}")
# 出错后继续监控
self.root.after(2000, self.start_performance_monitoring)
def refresh_processes(self):
"""刷新进程列表"""
try:
# 清除现有进程信息
for item in self.process_tree.get_children():
self.process_tree.delete(item)
# 获取所有进程
processes = []
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent', 'status', 'username', 'num_threads']):
try:
# 获取进程信息
process_info = proc.info
# 获取内存使用(MB)
memory_mb = round(process_info['memory_percent'] * psutil.virtual_memory().total / (1024**2) / 100, 2)
processes.append({
'pid': process_info['pid'],
'name': process_info['name'],
'cpu_percent': process_info['cpu_percent'],
'memory_mb': memory_mb,
'status': process_info['status'],
'username': process_info['username'] or "N/A",
'threads': process_info['num_threads']
})
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
# 排序
sort_key = self.sort_var.get()
if sort_key == "cpu":
processes.sort(key=lambda x: x['cpu_percent'], reverse=True)
else: # memory
processes.sort(key=lambda x: x['memory_mb'], reverse=True)
# 过滤并显示
filter_text = self.filter_var.get().lower()
for proc in processes:
# 过滤
if filter_text and filter_text not in proc['name'].lower():
continue
# 显示
self.process_tree.insert("", "end", values=(
proc['pid'],
proc['name'],
f"{proc['cpu_percent']:.1f}",
f"{proc['memory_mb']:.2f}",
proc['status'],
proc['username'],
proc['threads']
))
except Exception as e:
self.status_var.set(f"刷新进程列表时出错: {str(e)}")
def filter_processes(self, event=None):
"""过滤进程列表"""
self.refresh_processes()
def show_process_details(self, event):
"""显示选中进程的详细信息"""
try:
selected_item = self.process_tree.selection()
if not selected_item:
return
pid = int(self.process_tree.item(selected_item[0])['values'][0])
try:
process = psutil.Process(pid)
details = f"进程ID: {process.pid}\n"
details += f"名称: {process.name()}\n"
details += f"状态: {process.status()}\n"
details += f"CPU使用率: {process.cpu_percent()}%\n"
details += f"内存使用率: {process.memory_percent():.2f}%\n"
details += f"内存使用: {process.memory_info().rss / (1024**2):.2f} MB\n"
details += f"创建时间: {time.ctime(process.create_time())}\n"
details += f"工作目录: {process.cwd()}\n"
details += f"命令行: {' '.join(process.cmdline())}\n"
self.detail_text.delete(1.0, tk.END)
self.detail_text.insert(tk.END, details)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
self.detail_text.delete(1.0, tk.END)
self.detail_text.insert(tk.END, "无法获取进程信息")
except Exception as e:
self.status_var.set(f"显示进程详情时出错: {str(e)}")
def kill_process(self):
"""终止选中的进程"""
try:
selected_item = self.process_tree.selection()
if not selected_item:
return
pid = int(self.process_tree.item(selected_item[0])['values'][0])
# 确认对话框
if tk.messagebox.askyesno("确认", f"确定要终止进程 {pid} 吗?"):
try:
process = psutil.Process(pid)
process.terminate() # 尝试优雅地终止
# 等待进程终止
try:
process.wait(timeout=2)
except psutil.TimeoutExpired:
# 如果超时,强制终止
process.kill()
self.status_var.set(f"已终止进程 {pid}")
self.refresh_processes()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e:
self.status_var.set(f"无法终止进程 {pid}: {str(e)}")
except Exception as e:
self.status_var.set(f"终止进程时出错: {str(e)}")
if __name__ == "__main__":
# 确保中文显示正常
if platform.system() == "Windows":
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2)
except:
pass
root = tk.Tk()
app = HardwareInfoApp(root)
root.mainloop()
GRUD6 个月前
通告声明: 关于回帖问题 由于本站长要求,禁止刷1234等!存在恶意灌水回复,已开启自动审核制,自动封闭IP,禁止再次注册!请知晓!
有什么问题群内咨询 561116458
System7 个月前
网络技术QQ:561116458
科技之星①群:669812887
软件共享群:34008xxxx【因为是VIP软件不公开】
视频教程 短视频平台搜索:科技之星网络