-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomputer_info.py
More file actions
800 lines (667 loc) ยท 31.4 KB
/
computer_info.py
File metadata and controls
800 lines (667 loc) ยท 31.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
"""
Computer Info - System Information Viewer
A comprehensive hardware information viewer for Windows systems.
Author: GitHub User
License: MIT
"""
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import platform
import socket
import threading
from datetime import datetime
try:
import pythoncom
PYTHONCOM_AVAILABLE = True
except ImportError:
PYTHONCOM_AVAILABLE = False
try:
import wmi
WMI_AVAILABLE = True
except ImportError:
WMI_AVAILABLE = False
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
try:
import GPUtil
GPUTIL_AVAILABLE = True
except ImportError:
GPUTIL_AVAILABLE = False
class SystemInfo:
"""Class to gather system hardware information."""
def __init__(self):
self.wmi_obj = None
self._init_wmi()
def _init_wmi(self):
"""Initialize WMI connection with COM support."""
if WMI_AVAILABLE:
try:
if PYTHONCOM_AVAILABLE:
pythoncom.CoInitialize()
self.wmi_obj = wmi.WMI()
except Exception as e:
print(f"WMI initialization error: {e}")
self.wmi_obj = None
def get_os_info(self) -> dict:
"""Get operating system information."""
info = {}
if self.wmi_obj:
try:
for os_item in self.wmi_obj.Win32_OperatingSystem():
info["Operating System"] = os_item.Caption.strip() if os_item.Caption else "N/A"
info["Version"] = os_item.Version or "N/A"
info["Build Number"] = os_item.BuildNumber or "N/A"
info["Architecture"] = platform.machine()
info["Computer Name"] = socket.gethostname()
info["Install Date"] = str(os_item.InstallDate).split('.')[0] if os_item.InstallDate else "N/A"
info["Last Boot"] = str(os_item.LastBootUpTime).split('.')[0] if os_item.LastBootUpTime else "N/A"
break
except Exception as e:
print(f"OS info error: {e}")
if not info:
info = {
"Name": platform.system(),
"Version": platform.version(),
"Architecture": platform.machine(),
"Computer Name": socket.gethostname()
}
return info
def get_cpu_info(self) -> dict:
"""Get CPU information."""
info = {}
if self.wmi_obj:
try:
for cpu in self.wmi_obj.Win32_Processor():
info["Name"] = cpu.Name.strip() if cpu.Name else "N/A"
info["Manufacturer"] = cpu.Manufacturer or "N/A"
info["Cores"] = cpu.NumberOfCores or "N/A"
info["Threads"] = cpu.NumberOfLogicalProcessors or "N/A"
info["Max Clock Speed"] = f"{cpu.MaxClockSpeed} MHz" if cpu.MaxClockSpeed else "N/A"
info["L2 Cache"] = f"{cpu.L2CacheSize} KB" if cpu.L2CacheSize else "N/A"
info["L3 Cache"] = f"{cpu.L3CacheSize} KB" if cpu.L3CacheSize else "N/A"
info["Socket"] = cpu.SocketDesignation or "N/A"
break
except Exception as e:
print(f"CPU info error: {e}")
if PSUTIL_AVAILABLE:
try:
freq = psutil.cpu_freq()
if freq:
info["Current Frequency"] = f"{freq.current:.0f} MHz"
except Exception:
pass
try:
info["CPU Usage"] = f"{psutil.cpu_percent(interval=0.1):.1f}%"
except Exception:
pass
if not info:
info["Processor"] = platform.processor() or "N/A"
return info
def get_motherboard_info(self) -> dict:
"""Get motherboard information."""
info = {}
if self.wmi_obj:
try:
for board in self.wmi_obj.Win32_BaseBoard():
manufacturer = board.Manufacturer or ""
product = board.Product or ""
info["Motherboard"] = f"{manufacturer} {product}".strip() or "N/A"
info["Version"] = board.Version or "N/A"
info["Serial Number"] = board.SerialNumber or "N/A"
break
except Exception as e:
print(f"Motherboard info error: {e}")
try:
for bios in self.wmi_obj.Win32_BIOS():
info["BIOS Version"] = bios.SMBIOSBIOSVersion or "N/A"
info["BIOS Manufacturer"] = bios.Manufacturer or "N/A"
bios_date = str(bios.ReleaseDate).split('.')[0] if bios.ReleaseDate else ""
if bios_date and len(bios_date) >= 8:
info["BIOS Date"] = f"{bios_date[:4]}-{bios_date[4:6]}-{bios_date[6:8]}"
break
except Exception as e:
print(f"BIOS info error: {e}")
return info if info else {"Status": "Information not available"}
def get_gpu_info(self) -> list:
"""Get GPU information."""
gpus = []
if self.wmi_obj:
try:
for gpu in self.wmi_obj.Win32_VideoController():
# Skip Microsoft Basic Display Adapter
if gpu.Name and "Microsoft Basic" in gpu.Name:
continue
# Handle negative AdapterRAM (32-bit overflow for >2GB VRAM)
adapter_ram = gpu.AdapterRAM
if adapter_ram:
if adapter_ram < 0:
adapter_ram = adapter_ram + 2**32
ram_str = self._format_size(adapter_ram)
else:
ram_str = "N/A"
gpu_info = {
"Name": gpu.Name or "N/A",
"VRAM": ram_str,
"Driver Version": gpu.DriverVersion or "N/A",
"Resolution": f"{gpu.CurrentHorizontalResolution}x{gpu.CurrentVerticalResolution}"
if gpu.CurrentHorizontalResolution else "N/A",
"Refresh Rate": f"{gpu.CurrentRefreshRate} Hz" if gpu.CurrentRefreshRate else "N/A"
}
gpus.append(gpu_info)
except Exception as e:
print(f"GPU info error: {e}")
if GPUTIL_AVAILABLE:
try:
nvidia_gpus = GPUtil.getGPUs()
for i, gpu in enumerate(nvidia_gpus):
if i < len(gpus):
# Replace inaccurate WMI VRAM with GPUtil value (WMI has 32-bit limit)
gpus[i]["VRAM"] = f"{gpu.memoryTotal:.0f} MB"
gpus[i]["VRAM Used"] = f"{gpu.memoryUsed:.0f} MB"
gpus[i]["GPU Load"] = f"{gpu.load * 100:.1f}%"
gpus[i]["Temperature"] = f"{gpu.temperature}ยฐC" if gpu.temperature else "N/A"
else:
# Add NVIDIA GPU if not in WMI list
gpus.append({
"Name": gpu.name,
"VRAM": f"{gpu.memoryTotal:.0f} MB",
"VRAM Used": f"{gpu.memoryUsed:.0f} MB",
"GPU Load": f"{gpu.load * 100:.1f}%",
"Temperature": f"{gpu.temperature}ยฐC" if gpu.temperature else "N/A"
})
except Exception as e:
print(f"GPUtil error: {e}")
return gpus if gpus else [{"Status": "No GPU information available"}]
def get_ram_info(self) -> dict:
"""Get RAM information."""
info = {}
if PSUTIL_AVAILABLE:
mem = psutil.virtual_memory()
info["Total RAM"] = self._format_size(mem.total)
info["Used"] = self._format_size(mem.used)
info["Available"] = self._format_size(mem.available)
info["Usage"] = f"{mem.percent}%"
modules = []
if self.wmi_obj:
try:
for mem_module in self.wmi_obj.Win32_PhysicalMemory():
manufacturer = (mem_module.Manufacturer or "").strip()
part_number = (mem_module.PartNumber or "").strip()
module = {
"Capacity": self._format_size(int(mem_module.Capacity)) if mem_module.Capacity else "N/A",
"Speed": f"{mem_module.Speed} MHz" if mem_module.Speed else "N/A",
"Type": self._get_memory_type(mem_module.SMBIOSMemoryType) if hasattr(mem_module, 'SMBIOSMemoryType') else "DDR",
"Manufacturer": manufacturer if manufacturer else "Unknown",
"Part Number": part_number if part_number else "N/A",
"Slot": mem_module.DeviceLocator or "N/A"
}
modules.append(module)
except Exception as e:
print(f"RAM info error: {e}")
info["Modules"] = modules
info["Slots Used"] = len(modules)
return info
@staticmethod
def _get_memory_type(memory_type) -> str:
"""Convert SMBIOS memory type to human readable string."""
types = {
20: "DDR",
21: "DDR2",
22: "DDR2 FB-DIMM",
24: "DDR3",
26: "DDR4",
34: "DDR5"
}
return types.get(memory_type, "DDR")
def get_storage_info(self) -> list:
"""Get storage device information."""
drives = []
if self.wmi_obj:
try:
for disk in self.wmi_obj.Win32_DiskDrive():
drive_info = {
"Model": disk.Model or "N/A",
"Interface": disk.InterfaceType or "N/A",
"Size": self._format_size(int(disk.Size)) if disk.Size else "N/A",
"Serial": disk.SerialNumber.strip() if disk.SerialNumber else "N/A",
"Media Type": disk.MediaType or "N/A",
"Partitions": disk.Partitions or 0
}
# Try to determine if SSD or HDD
if disk.Model:
model_lower = disk.Model.lower()
if "ssd" in model_lower or "nvme" in model_lower:
drive_info["Type"] = "SSD"
elif "hdd" in model_lower:
drive_info["Type"] = "HDD"
else:
drive_info["Type"] = "Unknown"
drives.append(drive_info)
except Exception:
pass
# Add partition information
if PSUTIL_AVAILABLE:
try:
partitions = psutil.disk_partitions()
for partition in partitions:
try:
usage = psutil.disk_usage(partition.mountpoint)
partition_info = {
"Drive": partition.device,
"Mount Point": partition.mountpoint,
"File System": partition.fstype,
"Total": self._format_size(usage.total),
"Used": self._format_size(usage.used),
"Free": self._format_size(usage.free),
"Usage": f"{usage.percent}%"
}
drives.append(partition_info)
except Exception:
pass
except Exception:
pass
return drives if drives else [{"Status": "No storage information available"}]
def get_psu_info(self) -> dict:
"""Get power supply information (limited on Windows)."""
info = {
"Note": "PSU information is typically not available via software"
}
if self.wmi_obj:
try:
# Try to get battery info for laptops
for battery in self.wmi_obj.Win32_Battery():
info["Battery Name"] = battery.Name or "N/A"
info["Status"] = battery.Status or "N/A"
info["Design Capacity"] = f"{battery.DesignCapacity} mWh" if battery.DesignCapacity else "N/A"
info["Full Charge Capacity"] = f"{battery.FullChargeCapacity} mWh" if battery.FullChargeCapacity else "N/A"
info["Battery Type"] = battery.Chemistry or "N/A"
except Exception:
pass
try:
# Power plan info
for power in self.wmi_obj.Win32_PowerPlan():
if power.IsActive:
info["Active Power Plan"] = power.ElementName or "N/A"
break
except Exception:
pass
return info
def get_network_info(self) -> list:
"""Get network adapter information."""
adapters = []
if self.wmi_obj:
try:
for adapter in self.wmi_obj.Win32_NetworkAdapterConfiguration(IPEnabled=True):
ip_addr = adapter.IPAddress[0] if adapter.IPAddress else "N/A"
# Get IPv6 if available
ipv6 = ""
if adapter.IPAddress and len(adapter.IPAddress) > 1:
for ip in adapter.IPAddress[1:]:
if ":" in ip:
ipv6 = ip
break
adapter_info = {
"Adapter": adapter.Description or "N/A",
"IP Address": ip_addr,
"Subnet Mask": adapter.IPSubnet[0] if adapter.IPSubnet else "N/A",
"Gateway": adapter.DefaultIPGateway[0] if adapter.DefaultIPGateway else "N/A",
"MAC Address": adapter.MACAddress or "N/A",
"DHCP": "Yes" if adapter.DHCPEnabled else "No"
}
if ipv6:
adapter_info["IPv6"] = ipv6
adapters.append(adapter_info)
except Exception as e:
print(f"Network info error: {e}")
# Fallback to psutil if WMI fails
if not adapters and PSUTIL_AVAILABLE:
try:
net_if = psutil.net_if_addrs()
for iface, addrs in net_if.items():
for addr in addrs:
if addr.family.name == 'AF_INET':
adapters.append({
"Adapter": iface,
"IP Address": addr.address,
"Subnet Mask": addr.netmask or "N/A"
})
except Exception:
pass
return adapters if adapters else [{"Status": "No network information available"}]
@staticmethod
def _format_size(size_bytes) -> str:
"""Format bytes to human readable string."""
if size_bytes is None:
return "N/A"
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if abs(size_bytes) < 1024.0:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024.0
return f"{size_bytes:.2f} PB"
class ComputerInfoApp:
"""Main application class with GUI."""
def __init__(self):
self.root = tk.Tk()
self.root.title("Computer Info - System Information Viewer")
self.root.state('zoomed') # Start maximized
# Theme colors
self.dark_theme = {
"bg": "#1e1e2e",
"fg": "#cdd6f4",
"accent": "#89b4fa",
"secondary_bg": "#313244",
"border": "#45475a",
"header_bg": "#181825",
"success": "#a6e3a1",
"warning": "#f9e2af"
}
self.light_theme = {
"bg": "#eff1f5",
"fg": "#4c4f69",
"accent": "#1e66f5",
"secondary_bg": "#e6e9ef",
"border": "#ccd0da",
"header_bg": "#dce0e8",
"success": "#40a02b",
"warning": "#df8e1d"
}
self.current_theme = self.dark_theme
self.is_dark_mode = True
self.system_info = SystemInfo()
self.all_info = {}
self._setup_styles()
self._create_widgets()
self._apply_theme()
# Load data in background
self._load_data_async()
def _setup_styles(self):
"""Setup ttk styles."""
self.style = ttk.Style()
self.style.theme_use('clam')
def _apply_theme(self):
"""Apply the current theme to all widgets."""
theme = self.current_theme
self.root.configure(bg=theme["bg"])
# Configure styles
self.style.configure("TFrame", background=theme["bg"])
self.style.configure("TLabel", background=theme["bg"], foreground=theme["fg"])
self.style.configure("TButton", background=theme["secondary_bg"], foreground=theme["fg"])
self.style.configure("Header.TLabel", background=theme["header_bg"], foreground=theme["accent"],
font=("Segoe UI", 12, "bold"))
self.style.configure("Title.TLabel", background=theme["bg"], foreground=theme["accent"],
font=("Segoe UI", 16, "bold"))
self.style.configure("Info.TLabel", background=theme["secondary_bg"], foreground=theme["fg"],
font=("Consolas", 10))
# Configure canvas and scrollbar
self.canvas.configure(bg=theme["bg"])
self.scrollable_frame.configure(style="TFrame")
# Update header
self.header_frame.configure(style="TFrame")
self.title_label.configure(style="Title.TLabel")
# Refresh info panels
if self.all_info:
self._display_info()
def _create_widgets(self):
"""Create all GUI widgets."""
theme = self.current_theme
# Header frame
self.header_frame = ttk.Frame(self.root)
self.header_frame.pack(fill=tk.X, padx=10, pady=10)
self.title_label = ttk.Label(self.header_frame, text="๐ฅ๏ธ Computer Info", style="Title.TLabel")
self.title_label.pack(side=tk.LEFT)
# Buttons frame
btn_frame = ttk.Frame(self.header_frame)
btn_frame.pack(side=tk.RIGHT)
self.theme_btn = ttk.Button(btn_frame, text="๐ Dark", command=self._toggle_theme, width=10)
self.theme_btn.pack(side=tk.LEFT, padx=5)
self.refresh_btn = ttk.Button(btn_frame, text="๐ Refresh", command=self._refresh_data, width=10)
self.refresh_btn.pack(side=tk.LEFT, padx=5)
self.copy_btn = ttk.Button(btn_frame, text="๐ Copy", command=self._copy_to_clipboard, width=10)
self.copy_btn.pack(side=tk.LEFT, padx=5)
self.export_btn = ttk.Button(btn_frame, text="๐พ Export", command=self._export_to_file, width=10)
self.export_btn.pack(side=tk.LEFT, padx=5)
# Main content with scrollbar
content_frame = ttk.Frame(self.root)
content_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
self.canvas = tk.Canvas(content_frame, highlightthickness=0)
scrollbar = ttk.Scrollbar(content_frame, orient=tk.VERTICAL, command=self.canvas.yview)
self.scrollable_frame = ttk.Frame(self.canvas)
self.scrollable_frame.bind("<Configure>",
lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all")))
self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self.canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Bind canvas resize to update scrollable frame width
self.canvas.bind("<Configure>", self._on_canvas_configure)
# Bind mouse wheel
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
# Loading label
self.loading_label = ttk.Label(self.scrollable_frame, text="โณ Loading system information...",
font=("Segoe UI", 14))
self.loading_label.pack(pady=50)
# Status bar
self.status_var = tk.StringVar(value="Ready")
self.status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
self.status_bar.pack(fill=tk.X, side=tk.BOTTOM)
def _on_canvas_configure(self, event):
"""Update scrollable frame width when canvas resizes."""
self.canvas.itemconfig(self.canvas.find_withtag("all")[0], width=event.width)
def _on_mousewheel(self, event):
"""Handle mouse wheel scrolling."""
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def _toggle_theme(self):
"""Toggle between dark and light theme."""
self.is_dark_mode = not self.is_dark_mode
self.current_theme = self.dark_theme if self.is_dark_mode else self.light_theme
self.theme_btn.configure(text="๐ Dark" if self.is_dark_mode else "โ๏ธ Light")
self._apply_theme()
def _load_data_async(self):
"""Load system data in background thread."""
def load():
# Initialize COM for this thread (required for WMI)
if PYTHONCOM_AVAILABLE:
try:
pythoncom.CoInitialize()
except Exception:
pass
# Create a new SystemInfo instance for this thread
self.system_info = SystemInfo()
self._gather_all_info()
if PYTHONCOM_AVAILABLE:
try:
pythoncom.CoUninitialize()
except Exception:
pass
self.root.after(0, self._on_data_loaded)
thread = threading.Thread(target=load, daemon=True)
thread.start()
def _gather_all_info(self):
"""Gather all system information."""
self.all_info = {
"Operating System": self.system_info.get_os_info(),
"CPU": self.system_info.get_cpu_info(),
"Motherboard": self.system_info.get_motherboard_info(),
"GPU": self.system_info.get_gpu_info(),
"RAM": self.system_info.get_ram_info(),
"Storage": self.system_info.get_storage_info(),
"Power": self.system_info.get_psu_info(),
"Network": self.system_info.get_network_info()
}
def _on_data_loaded(self):
"""Called when data loading is complete."""
self.loading_label.destroy()
self._display_info()
self.status_var.set(f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
def _display_info(self):
"""Display all system information."""
# Clear existing widgets
for widget in self.scrollable_frame.winfo_children():
widget.destroy()
theme = self.current_theme
# Create grid layout - 2 columns
left_frame = ttk.Frame(self.scrollable_frame)
left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
right_frame = ttk.Frame(self.scrollable_frame)
right_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(5, 0))
# Left column
left_sections = ["Operating System", "CPU", "Motherboard", "Power"]
for section in left_sections:
if section in self.all_info:
self._create_section(left_frame, section, self.all_info[section])
# Right column
right_sections = ["RAM", "GPU", "Storage", "Network"]
for section in right_sections:
if section in self.all_info:
self._create_section(right_frame, section, self.all_info[section])
def _create_section(self, parent, title, data):
"""Create a section panel for displaying info."""
theme = self.current_theme
# Section frame
section_frame = tk.Frame(parent, bg=theme["secondary_bg"], relief=tk.FLAT, bd=1)
section_frame.pack(fill=tk.X, pady=5, padx=2)
# Header
header = tk.Label(section_frame, text=f" {self._get_icon(title)} {title}",
bg=theme["header_bg"], fg=theme["accent"],
font=("Segoe UI", 11, "bold"), anchor="w")
header.pack(fill=tk.X, padx=1, pady=1)
# Content
content_frame = tk.Frame(section_frame, bg=theme["secondary_bg"])
content_frame.pack(fill=tk.X, padx=10, pady=10)
if isinstance(data, dict):
self._display_dict(content_frame, data, theme)
elif isinstance(data, list):
for i, item in enumerate(data):
if i > 0:
separator = tk.Frame(content_frame, bg=theme["border"], height=1)
separator.pack(fill=tk.X, pady=5)
if isinstance(item, dict):
self._display_dict(content_frame, item, theme)
def _display_dict(self, parent, data, theme, indent=0):
"""Display dictionary data."""
for key, value in data.items():
if key == "Modules" and isinstance(value, list):
# Special handling for RAM modules
module_label = tk.Label(parent, text=f"{' ' * indent}๐ฆ Memory Modules:",
bg=theme["secondary_bg"], fg=theme["warning"],
font=("Consolas", 10, "bold"), anchor="w")
module_label.pack(fill=tk.X, pady=(5, 2))
for i, module in enumerate(value):
module_header = tk.Label(parent, text=f"{' ' * (indent + 1)}Slot {i + 1}:",
bg=theme["secondary_bg"], fg=theme["success"],
font=("Consolas", 10), anchor="w")
module_header.pack(fill=tk.X)
self._display_dict(parent, module, theme, indent + 2)
else:
row_frame = tk.Frame(parent, bg=theme["secondary_bg"])
row_frame.pack(fill=tk.X, pady=1)
key_label = tk.Label(row_frame, text=f"{' ' * indent}{key}:",
bg=theme["secondary_bg"], fg=theme["fg"],
font=("Consolas", 10), width=25, anchor="w")
key_label.pack(side=tk.LEFT)
value_label = tk.Label(row_frame, text=str(value),
bg=theme["secondary_bg"], fg=theme["accent"],
font=("Consolas", 10), anchor="w")
value_label.pack(side=tk.LEFT, fill=tk.X, expand=True)
@staticmethod
def _get_icon(section):
"""Get icon for section."""
icons = {
"Operating System": "๐ป",
"CPU": "๐ฒ",
"Motherboard": "๐ง",
"GPU": "๐ฎ",
"RAM": "๐",
"Storage": "๐พ",
"Power": "๐",
"Network": "๐"
}
return icons.get(section, "๐")
def _refresh_data(self):
"""Refresh system information."""
self.status_var.set("Refreshing...")
# Clear and show loading
for widget in self.scrollable_frame.winfo_children():
widget.destroy()
loading = ttk.Label(self.scrollable_frame, text="โณ Refreshing system information...",
font=("Segoe UI", 14))
loading.pack(pady=50)
self._load_data_async()
def _copy_to_clipboard(self):
"""Copy all info to clipboard."""
text = self._generate_text_report()
self.root.clipboard_clear()
self.root.clipboard_append(text)
self.status_var.set("โ
Copied to clipboard!")
self.root.after(3000, lambda: self.status_var.set("Ready"))
def _export_to_file(self):
"""Export info to text file."""
filename = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
initialfile=f"computer_info_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
)
if filename:
try:
text = self._generate_text_report()
with open(filename, 'w', encoding='utf-8') as f:
f.write(text)
self.status_var.set(f"โ
Exported to {filename}")
self.root.after(3000, lambda: self.status_var.set("Ready"))
except Exception as e:
messagebox.showerror("Export Error", f"Failed to export: {str(e)}")
def _generate_text_report(self) -> str:
"""Generate text report of all info."""
lines = ["=" * 60]
lines.append("COMPUTER INFORMATION REPORT")
lines.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
lines.append("=" * 60)
lines.append("")
for section, data in self.all_info.items():
lines.append(f"{'โ' * 40}")
lines.append(f"[{section.upper()}]")
lines.append(f"{'โ' * 40}")
if isinstance(data, dict):
lines.extend(self._dict_to_lines(data))
elif isinstance(data, list):
for i, item in enumerate(data):
if i > 0:
lines.append("")
if isinstance(item, dict):
lines.extend(self._dict_to_lines(item))
lines.append("")
return "\n".join(lines)
def _dict_to_lines(self, data, indent=0) -> list:
"""Convert dictionary to lines."""
lines = []
for key, value in data.items():
if key == "Modules" and isinstance(value, list):
lines.append(f"{' ' * indent}Memory Modules:")
for i, module in enumerate(value):
lines.append(f"{' ' * (indent + 1)}Slot {i + 1}:")
lines.extend(self._dict_to_lines(module, indent + 2))
else:
lines.append(f"{' ' * indent}{key}: {value}")
return lines
def run(self):
"""Run the application."""
self.root.mainloop()
def main():
"""Main entry point."""
# Check dependencies
missing = []
if not WMI_AVAILABLE:
missing.append("wmi")
if not PSUTIL_AVAILABLE:
missing.append("psutil")
if missing:
print(f"Warning: Missing optional dependencies: {', '.join(missing)}")
print("Install with: pip install " + " ".join(missing))
print("The application will run with limited functionality.\n")
app = ComputerInfoApp()
app.run()
if __name__ == "__main__":
main()