import os import tkinter as tk from tkinter import filedialog from tkinter import ttk from zipfile import ZipFile selected_items = [] def toggle_selection(event): item = tree.item(tree.focus()) file_path = item['text'] if item['tags'] == ('file',): if file_path in selected_items: selected_items.remove(file_path) else: selected_items.append(file_path) update_selection_label() def select_items(): if selected_items: zip_file = 'selected_items.zip' with ZipFile(zip_file, 'w') as zf: for item in selected_items: arcname = os.path.relpath(item, target_path) if os.path.isfile(item): zf.write(item, arcname) elif os.path.isdir(item): for root, dirs, files in os.walk(item): for file in files: file_path = os.path.join(root, file) arcname = os.path.relpath(file_path, target_path) zf.write(file_path, arcname) result_label.config(text=f'文件已打包为 {zip_file}') selected_items.clear() update_selection_label() def update_selection_label(): selection_label.config(text=f'已选中 {len(selected_items)} 个文件/文件夹') def build_tree(parent, directory): for item in os.listdir(directory): item_path = os.path.join(directory, item) if os.path.isdir(item_path): item_node = tree.insert(parent, 'end', text=item, open=False, tags=('folder',)) build_tree(item_node, item_path) else: tree.insert(parent, 'end', text=item, tags=('file',)) def toggle_checkbox(event): item_id = tree.identify_row(event.y) if item_id: is_checked = tree.tag_has('checked', item_id) if is_checked: tree.tag_remove('checked', item_id) else: tree.tag_add('checked', item_id) # 创建主窗口 root = tk.Tk() root.title("文件选择") root.geometry("600x400") # 计算窗口居中的位置 screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() window_width = 600 window_height = 400 x = (screen_width - window_width) // 2 y = (screen_height - window_height) // 2 root.geometry(f"{window_width}x{window_height}+{x}+{y}") # 选择目标文件夹 target_path = os.path.join(os.getcwd(), 'target/classes/') # 创建选择按钮 select_button = tk.Button(root, text='打包选中的文件或文件夹', command=select_items) select_button.pack(pady=10) # 创建目录树 tree = ttk.Treeview(root, selectmode='none') tree.pack(fill='both', expand=True) # 创建滚动条 scrollbar = ttk.Scrollbar(root, orient='vertical', command=tree.yview) scrollbar.pack(side='right', fill='y') tree.configure(yscrollcommand=scrollbar.set) # 添加当前目录下的文件和文件夹到目录树 build_tree('', target_path) # 创建结果标签 result_label = tk.Label(root, text='') result_label.pack() # 创建已选中文件数标签 selection_label = tk.Label(root, text='') selection_label.pack() # 绑定鼠标点击事件 tree.bind('', toggle_checkbox) # 启动主循环 root.mainloop()