用Python语言,利用 tk包,实现选择2个目录,进行COPY功能
在日常办公中经常需要进行文件的备份保存,使用Python语言,利用TK包,代码主要实现如下功能:
1、1个按钮选择源文件路径。
2、1个按钮选择目标文件路径;
3、1个按钮用于执行copy任务;
4、复制中如果1个文件出错,跳过继续执行下1个;并把出错文件记录到出错列表中;
5、如果遇到重复文件名称,自动进行覆盖;
6、1个展示信息展示区域,显示总计COPY文件数量,复制出错的所有文件名;
import os
import shutil
import tkinter as tk
from tkinter import filedialog, messageboxclass FileCopyApp:def __init__(self, root):self.root = rootself.root.title("File Copy Tool")# 初始化变量self.source_path = tk.StringVar()self.destination_path = tk.StringVar()self.copy_count = 0self.error_files = []# 创建UI组件self.create_widgets()def create_widgets(self):# 源路径选择按钮和显示框tk.Label(self.root, text="Source Path:").grid(row=0, column=0, padx=10, pady=5)tk.Entry(self.root, textvariable=self.source_path, width=50).grid(row=0, column=1, padx=10, pady=5)tk.Button(self.root, text="Browse", command=self.browse_source).grid(row=0, column=2, padx=10, pady=5)# 目标路径选择按钮和显示框tk.Label(self.root, text="Destination Path:").grid(row=1, column=0, padx=10, pady=5)tk.Entry(self.root, textvariable=self.destination_path, width=50).grid(row=1, column=1, padx=10, pady=5)tk.Button(self.root, text="Browse", command=self.browse_destination).grid(row=1, column=2, padx=10, pady=5)# 执行复制任务按钮tk.Button(self.root, text="Start Copy", command=self.start_copy).grid(row=2,columnspan = 3,padx = 10 ,pady = 20)# 信息展示区域self.info_text = tk.Text(self.root,height = 15,width = 70)self.info_text.grid(row = 3,columnspan = 3,padx = 10 ,pady = 20 )def browse_source(self):path=filedialog.askdirectory()if path:self.source_path.set(path)def browse_destination(self):path=filedialog.askdirectory()if path:self.destination_path.set(path)def start_copy(self):source_dir=self.source_path.get()destination_dir=self.destination_path.get()if not source_dir or not destination_dir:messagebox.showerror("Error","Please select both source and destination paths.")returnself.copy_count = 0 self.error_files.clear()for root_dir ,dirs ,files in os.walk(source_dir):for file in files:source_file_path=os.path.join(root_dir,file)relative_path=os.path.relpath(root_dir ,source_dir)dest_file_path=os.path.join(destination_dir ,relative_path,file)try :os.makedirs(os.path.dirname(dest_file_path),exist_ok=True)shutil.copy2(source_file_path,dest_file_path) # 自动覆盖同名文件self.copy_count += 1 except Exception as e :print(f"Error copying {source_file_path} to {dest_file_path}: {e}")self.error_files.append(source_file_path)self.display_info()def display_info(self):info_message=f"Total files copied : {self.copy_count}\n"if self.error_files:info_message += f"\nFiles failed to copy ({len(self.error_files)}):\n"info_message += "\n".join(self.error_files)else :info_message +="\nAll files copied successfully."# 清空并更新信息展示区域self.info_text.delete(1.0 ,tk.END)self.info_text.insert(tk.END ,info_message)if __name__ == "__main__":root=tk.Tk()app = FileCopyApp(root)root.mainloop()