要实现这样一个功能,我们需要创建一个Tkinter GUI,其中包含复选框让用户选择常见的垃圾目录,一个文本框供用户输入自定义目录,以及一个按钮来触发清理操作并实时显示清理进度。以下是一个简化的实现示例,注意在实际应用中需要确保安全性和准确性,避免误删重要文件。

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import os
import shutil
def clear_junk_dirs(directories):
"""清除指定目录下的垃圾文件和文件夹"""
cleared_size = 0
for directory in directories:
if os.path.exists(directory):
for item in os.listdir(directory):
item_path = os.path.join(directory, item)
if os.path.isfile(item_path):
try:
os.remove(item_path)
cleared_size += os.path.getsize(item_path)
log_text.insert(tk.END, f"Deleted: {item_path}, Size: {os.path.getsize(item_path)} bytes\n")
except Exception as e:
log_text.insert(tk.END, f"Error deleting {item_path}: {str(e)}\n")
elif os.path.isdir(item_path):
try:
shutil.rmtree(item_path)
cleared_size += sum(os.path.getsize(os.path.join(dp, fn)) for dp, _, fn in os.walk(item_path))
log_text.insert(tk.END, f"Removed directory: {item_path}\n")
except Exception as e:
log_text.insert(tk.END, f"Error removing directory {item_path}: {str(e)}\n")
log_text.insert(tk.END, f"Cleared total size: {cleared_size} bytes\n")
messagebox.showinfo("清理完成", f"共清理了 {cleared_size} 字节的空间。")
def on_clean_click():
selected_dirs = [dir for dir, var in zip(common_dirs, common_vars) if var.get()]
custom_dir = custom_entry.get()
if custom_dir and os.path.isdir(custom_dir):
selected_dirs.append(custom_dir)
clear_junk_dirs(selected_dirs)
root = tk.Tk()
root.title("系统垃圾清理工具")
# 常见垃圾目录复选框
common_dirs = ["%TEMP%", "%USERPROFILE%\\AppData\\Local\\Temp", "%USERPROFILE%\\Downloads\\*.*"]
common_vars = [tk.BooleanVar() for _ in common_dirs]
for i, (dir_name, var) in enumerate(zip(common_dirs, common_vars)):
cb = ttk.Checkbutton(root, text=os.path.expandvars(dir_name), variable=var)
cb.grid(row=i, column=0, sticky=tk.W)
# 自定义目录输入框
tk.Label(root, text="自定义目录:").grid(row=len(common_dirs), column=0, sticky=tk.W)
custom_entry = ttk.Entry(root)
custom_entry.grid(row=len(common_dirs), column=1)
# 清理按钮
clean_button = ttk.Button(root, text="一键清理", command=on_clean_click)
clean_button.grid(row=len(common_dirs)+1, columnspan=2)
# 清理日志显示区
log_text = tk.Text(root, height=10)
log_text.grid(row=len(common_dirs)+2, columnspan=2)
root.mainloop()
代码分析
cleared_size += sum(os.path.getsize(os.path.join(dp, fn)) for dp, _, fn in os.walk(item_path))
这段代码是用来计算一个目录(item_path)及其所有子目录下的所有文件的大小总和。这里是如何工作的:
os.walk(item_path)会遍历item_path指定的目录以及其所有的子目录。对于每一个遍历到的目录,它会返回一个三元组(dirpath, dirnames, filenames):dp是当前目录的路径(dirpath)。dn是当前目录下的子目录名列表(dirnames)。fn是当前目录下的文件名列表(filenames)。
这段代码创建了一个Tkinter窗口,其中包含了几个复选框对应一些常见的垃圾文件目录(例如 %TEMP%, %USERPROFILE%\\AppData\\Local\\Temp, %USERPROFILE%\\Downloads\\*.*,这些路径在实际执行前会被环境变量展开)。用户可以选择这些预设的目录,也可以在文本框中输入自定义目录进行清理。点击“一键清理”按钮后,clear_junk_dirs 函数会被调用,它遍历选中的目录,尝试删除其中的文件和子目录,并在文本框中实时记录清理的文件路径、文件名及文件大小。
安全警告:在实际应用中,直接删除文件和目录是非常危险的操作,尤其是涉及到系统或用户个人文件时。务必确保有适当的错误处理和确认机制,避免数据丢失。此外,考虑到不同操作系统和环境的差异,上述代码中的路径可能需要根据实际情况调整。
当前文章价值4.85元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

评论已关闭!