class SCLMultiProcessor:
def init(self, root):
self.root = root
# 创建日志目录
self.log_dir = “logs”
self.root.title(“SCL文件处理系统”)
self.root.geometry(“1100x750”) # 增加窗口尺寸以适应新控件
# 初始化变量 self.color_detector = ExcelColorDetector() self.stats_processor = SCLRuleProcessor() self.release_processor = ReleaseSCLProcessor() self.empty_cell_detector = EnhancedEmptyCellDetector(self.color_detector) self.progress_var = tk.DoubleVar() os.makedirs(self.log_dir, exist_ok=True) # 初始化日志系统 self.current_log_file = None self.setup_logger() # 创建主框架 self.main_frame = ttk.Frame(root, padding="10") self.main_frame.pack(fill=tk.BOTH, expand=True) # 创建UI self.create_ui() # 记录UI初始化完成 self.logger.info("用户界面初始化完成") def toggle_config_fields(self): """根据操作模式显示/隐藏相关配置字段""" mode = self.operation_mode.get() self.checksheet_frame.pack_forget() # 隐藏CheckSheet路径 self.input_frame.pack_forget() # 隐藏统计表路径 self.excel_compare_frame.pack_forget() # 统计模式:显示统计表路径,隐藏CheckSheet路径 if mode == "stats" : self.input_frame.pack(fill=tk.X, pady=5) # 显示统计表路径 self.scl_folder_frame.pack(fill=tk.X, pady=5) self.logger.info("切换到统计模式,显示统计表路径") # SCL格式检查模式:隐藏统计表路径,显示CheckSheet路径 elif mode == "empty_check": self.checksheet_frame.pack(fill=tk.X, pady=5) # 显示CheckSheet路径 self.logger.info("切换到SCL格式检查模式,显示CheckSheet路径") # Release模式:显示统计表路径,隐藏CheckSheet路径 elif mode == "release": self.scl_folder_frame.pack(fill=tk.X, pady=5) self.input_frame.pack(fill=tk.X, pady=5) # 显示统计表路径 self.logger.info("切换到Release模式,显示统计表路径") elif mode == "excel_compare": self.scl_folder_frame.pack_forget() self.excel_compare_frame.pack(fill=tk.X, pady=5) self.logger.info("切换到Excel比较模式") def browse_compare_folder(self): """浏览比较文件夹""" folder_path = filedialog.askdirectory(title="选择比较文件夹(应包含before和after子文件夹)") if folder_path: self.compare_folder_var.set(folder_path) self.logger.info(f"已选择比较文件夹: {folder_path}") def create_ui(self): """创建用户界面""" # 操作模式选择区域 mode_frame = ttk.LabelFrame(self.main_frame, text="操作模式", padding="10") mode_frame.pack(fill=tk.X, pady=5) # 添加操作模式单选按钮 self.operation_mode = tk.StringVar(value="stats") # 默认选择统计模式 ttk.Radiobutton(mode_frame, text="统计release前的数据", variable=self.operation_mode, value="stats", command=self.toggle_config_fields).pack(side=tk.LEFT, padx=10) ttk.Radiobutton(mode_frame, text="SCL格式检查", variable=self.operation_mode, value="empty_check", command=self.toggle_config_fields).pack(side=tk.LEFT, padx=10) ttk.Radiobutton(mode_frame, text="统计release后的数据", variable=self.operation_mode, value="release", command=self.toggle_config_fields).pack(side=tk.LEFT, padx=10) # 添加Excel比较模式 ttk.Radiobutton(mode_frame, text="Excel文件比较", variable=self.operation_mode, value="excel_compare", command=self.toggle_config_fields).pack(side=tk.LEFT, padx=10) # 文件选择区域 - 放在操作模式后面 file_frame = ttk.LabelFrame(self.main_frame, text="文件选择", padding="10") file_frame.pack(fill=tk.X, pady=5) # 输入文件选择 - 统计表路径(统计模式需要) self.input_frame = ttk.Frame(file_frame) ttk.Label(self.input_frame, text="统计表:").pack(side=tk.LEFT, padx=5) self.input_path_var = tk.StringVar() input_entry = ttk.Entry(self.input_frame, textvariable=self.input_path_var, width=70) input_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5) ttk.Button(self.input_frame, text="浏览...", command=self.browse_input_file).pack(side=tk.LEFT, padx=5) self.input_frame.pack(fill=tk.X, pady=5) # 默认显示 # 配置区域 config_frame = ttk.LabelFrame(self.main_frame, text="处理配置", padding="10") config_frame.pack(fill=tk.X, pady=5) # 添加SCL文件夹路径输入 self.scl_folder_frame = ttk.Frame(config_frame) self.scl_folder_frame.pack(fill=tk.X, pady=5) ttk.Label(self.scl_folder_frame, text="SCL文件夹路径:").grid(row=0, column=0, padx=5, sticky=tk.W) self.scl_folder_var = tk.StringVar() scl_folder_entry = ttk.Entry(self.scl_folder_frame, textvariable=self.scl_folder_var, width=60) scl_folder_entry.grid(row=0, column=1, padx=5, sticky=tk.W) ttk.Button(self.scl_folder_frame, text="浏览...", command=self.browse_scl_folder).grid(row=0, column=2, padx=5, sticky=tk.W) # 搜索选项 search_frame = ttk.Frame(config_frame) search_frame.pack(fill=tk.X, pady=5) ttk.Label(search_frame, text="文件前缀:").grid(row=0, column=0, padx=5, sticky=tk.W) self.prefix_var = tk.StringVar(value="SCL_") ttk.Entry(search_frame, textvariable=self.prefix_var, width=10).grid(row=0, column=1, padx=5, sticky=tk.W) # 添加CheckSheet路径输入(SCL格式检查模式需要) self.checksheet_frame = ttk.Frame(config_frame) ttk.Label(self.checksheet_frame, text="CheckSheet路径:").grid(row=0, column=0, padx=5, sticky=tk.W) self.checksheet_path_var = tk.StringVar() checksheet_entry = ttk.Entry(self.checksheet_frame, textvariable=self.checksheet_path_var, width=60) checksheet_entry.grid(row=0, column=1, padx=5, sticky=tk.W) ttk.Button(self.checksheet_frame, text="浏览...", command=self.browse_checksheet_path).grid(row=0, column=2, padx=5, sticky=tk.W) self.checksheet_frame.pack_forget() # 默认隐藏 # Excel比较配置区域 self.excel_compare_frame = ttk.Frame(config_frame) self.excel_compare_frame.pack(fill=tk.X, pady=5) # Before文件夹选择 ttk.Label(self.excel_compare_frame, text="Before文件夹:").grid(row=0, column=0, padx=5, sticky=tk.W) self.before_folder_var = tk.StringVar() before_folder_entry = ttk.Entry(self.excel_compare_frame, textvariable=self.before_folder_var, width=60) before_folder_entry.grid(row=0, column=1, padx=5, sticky=tk.W) ttk.Button(self.excel_compare_frame, text="浏览...", command=self.browse_before_folder).grid(row=0, column=2, padx=5, sticky=tk.W) # After文件夹选择 ttk.Label(self.excel_compare_frame, text="After文件夹:").grid(row=1, column=0, padx=5, sticky=tk.W) self.after_folder_var = tk.StringVar() after_folder_entry = ttk.Entry(self.excel_compare_frame, textvariable=self.after_folder_var, width=60) after_folder_entry.grid(row=1, column=1, padx=5, sticky=tk.W) ttk.Button(self.excel_compare_frame, text="浏览...", command=self.browse_after_folder).grid(row=1, column=2, padx=5, sticky=tk.W) # 相似度阈值设置 ttk.Label(self.excel_compare_frame, text="相似度阈值:").grid(row=2, column=0, padx=5, sticky=tk.W) self.similarity_var = tk.DoubleVar(value=0.7) ttk.Scale(self.excel_compare_frame, from_=0.1, to=1.0, variable=self.similarity_var, orient="horizontal", length=200).grid(row=2, column=1, padx=5, sticky=tk.W) self.similarity_label = ttk.Label(self.excel_compare_frame, textvariable=self.similarity_var) self.similarity_label.grid(row=2, column=2, padx=5, sticky=tk.W) # 默认隐藏 self.excel_compare_frame.pack_forget() # 添加性能提示 ttk.Label(config_frame, text="(表头固定在第3行,数据从第4行开始)").pack(anchor=tk.W, padx=5, pady=2) # 日志选项 log_frame = ttk.Frame(config_frame) log_frame.pack(fill=tk.X, pady=5) ttk.Label(log_frame, text="日志级别:").grid(row=0, column=0, padx=5, sticky=tk.W) self.log_level_var = tk.StringVar(value="INFO") log_level_combo = ttk.Combobox( log_frame, textvariable=self.log_level_var, width=10, state="readonly" ) log_level_combo['values'] = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL') log_level_combo.grid(row=0, column=1, padx=5, sticky=tk.W) log_level_combo.bind("<<ComboboxSelected>>", self.change_log_level) # 处理按钮 btn_frame = ttk.Frame(self.main_frame) btn_frame.pack(fill=tk.X, pady=10) ttk.Button(btn_frame, text="开始处理", command=self.process_file).pack(side=tk.LEFT, padx=5) ttk.Button(btn_frame, text="查看日志", command=self.view_log).pack(side=tk.LEFT, padx=5) ttk.Button(btn_frame, text="导出配置", command=self.export_config).pack(side=tk.LEFT, padx=5) ttk.Button(btn_frame, text="加载配置", command=self.load_config).pack(side=tk.LEFT, padx=5) ttk.Button(btn_frame, text="退出", command=self.root.destroy).pack(side=tk.RIGHT, padx=5) # 进度条 progress_frame = ttk.Frame(self.main_frame) progress_frame.pack(fill=tk.X, pady=5) ttk.Label(progress_frame, text="处理进度:").pack(side=tk.LEFT, padx=5) self.progress_bar = ttk.Progressbar( progress_frame, variable=self.progress_var, maximum=100, length=700 ) self.progress_bar.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5) self.progress_label = ttk.Label(progress_frame, text="0%") self.progress_label.pack(side=tk.LEFT, padx=5) # 结果展示区域 result_frame = ttk.LabelFrame(self.main_frame, text="处理结果", padding="10") result_frame.pack(fill=tk.BOTH, expand=True, pady=5) # 结果文本框 self.result_text = scrolledtext.ScrolledText( result_frame, wrap=tk.WORD, height=20 ) self.result_text.pack(fill=tk.BOTH, expand=True) self.result_text.config(state=tk.DISABLED) # 状态栏 self.status_var = tk.StringVar(value="就绪") status_bar = ttk.Label(self.main_frame, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W) status_bar.pack(fill=tk.X, pady=5) self.logger.info("UI创建完成") def browse_checksheet_path(self): """浏览CheckSheet文件夹""" folder_path = filedialog.askdirectory(title="选择CheckSheet文件夹") if folder_path: self.checksheet_path_var.set(folder_path) self.logger.info(f"已选择CheckSheet文件夹: {folder_path}") def browse_before_folder(self): """浏览Before文件夹""" folder_path = filedialog.askdirectory(title="选择Before文件夹") if folder_path: self.before_folder_var.set(folder_path) self.logger.info(f"已选择Before文件夹: {folder_path}") def browse_after_folder(self): """浏览After文件夹""" folder_path = filedialog.askdirectory(title="选择After文件夹") if folder_path: self.after_folder_var.set(folder_path) self.logger.info(f"已选择After文件夹: {folder_path}") def setup_logger(self): """配置日志记录器""" # 创建唯一日志文件名 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") self.current_log_file = os.path.join(self.log_dir, f"scl_processor_{timestamp}.log") # 创建或获取日志记录器 self.logger = logging.getLogger("SCLProcessor") self.logger.setLevel(logging.INFO) # 移除所有现有处理器 for handler in self.logger.handlers[:]: self.logger.removeHandler(handler) # 创建文件处理器 file_handler = logging.FileHandler(self.current_log_file, encoding='utf-8') file_handler.setLevel(logging.INFO) # 创建控制台处理器 console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) # 创建日志格式 formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) file_handler.setFormatter(formatter) console_handler.setFormatter(formatter) # 添加处理器 self.logger.addHandler(file_handler) self.logger.addHandler(console_handler) # 记录日志初始化信息 self.logger.info(f"日志系统已初始化,日志文件: {self.current_log_file}") self.logger.info(f"日志目录: {os.path.abspath(self.log_dir)}") def change_log_level(self, event=None): """动态更改日志级别""" try: # 获取选择的日志级别 level_str = self.log_level_var.get() log_level = getattr(logging, level_str.upper()) # 更新日志记录器级别 self.logger.setLevel(log_level) # 更新所有处理器的级别 for handler in self.logger.handlers: handler.setLevel(log_level) self.logger.info(f"日志级别已成功更改为: {level_str}") self.status_var.set(f"日志级别: {level_str}") except AttributeError: self.logger.error(f"无效的日志级别: {level_str}") messagebox.showerror("错误", f"无效的日志级别: {level_str}") except Exception as e: self.logger.exception("更改日志级别时发生错误") messagebox.showerror("错误", f"更改日志级别失败: {str(e)}") def browse_input_file(self): """浏览输入文件""" file_path = filedialog.askopenfilename( filetypes=[("Excel 文件", "*.xlsx *.xls"), ("所有文件", "*.*")] ) if file_path: self.input_path_var.set(file_path) self.logger.info(f"已选择输入文件: {file_path}") def browse_scl_folder(self): """浏览SCL文件夹""" folder_path = filedialog.askdirectory(title="选择SCL文件夹") if folder_path: self.scl_folder_var.set(folder_path) self.logger.info(f"已选择SCL文件夹: {folder_path}") def highlight_cell(self, sheet, row, col, color="FFFF0000"): """为单元格设置背景色""" try: fill = PatternFill(start_color=color, end_color=color, fill_type="solid") sheet.cell(row=row, column=col).fill = fill return True except Exception as e: self.logger.error(f"设置单元格颜色失败: {str(e)}") return False def create_column_letter_map(self): """创建列号到列字母的映射""" column_letter_map = {} # 生成A-Z列 for i in range(1, 27): column_letter_map[i] = chr(64 + i) # 生成AA-AZ列 for i in range(1, 27): column_letter_map[26 + i] = f"A{chr(64 + i)}" # 生成BA-BZ列 for i in range(1, 27): column_letter_map[52 + i] = f"B{chr(64 + i)}" # 生成CA-CZ列 for i in range(1, 27): column_letter_map[78 + i] = f"C{chr(64 + i)}" # 添加已知的特殊列 column_letter_map.update({ 16: "P", 23: "W", 27: "AA", 30: "AD", 34: "AH", 37: "AK", 42: "AP", 45: "AS", 50: "AX", 53: "BA", 57: "BE", 60: "BH", 62: "BL", 65: "BO", 71: "BS", 74: "BV", 78: "BZ", 85: "CG" }) return column_letter_map def process_file(self): """处理文件 - 根据操作模式执行不同处理流程""" operation_mode = self.operation_mode.get() # 重置结果 self.result_text.config(state=tk.NORMAL) self.result_text.delete(1.0, tk.END) self.result_text.insert(tk.END, "开始处理...\n") self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) self.status_var.set("开始处理文件...") self.root.update() try: # 每次处理前重新初始化日志系统 self.setup_logger() # 记录处理开始信息 self.logger.info("=" * 50) self.logger.info(f"开始处理: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") self.logger.info(f"操作模式: {operation_mode}") self.logger.info("=" * 50) # 更新UI显示当前日志文件 self.status_var.set(f"当前日志: {os.path.basename(self.current_log_file)}") # 获取公共配置参数 scl_folder = self.scl_folder_var.get() prefix = self.prefix_var.get() # 根据操作模式执行不同处理流程 if operation_mode == "stats": self.process_stats_mode(scl_folder, prefix) elif operation_mode == "empty_check": self.process_empty_check_mode(scl_folder, prefix) elif operation_mode == "release": self.process_release_mode(scl_folder, prefix) elif operation_mode == "excel_compare": self.process_excel_comparison() else: messagebox.showerror("错误", f"未知操作模式: {operation_mode}") self.logger.error(f"未知操作模式: {operation_mode}") except Exception as e: error_msg = f"处理文件时出错: {str(e)}" self.logger.exception(f"处理文件时出错: {str(e)}") messagebox.showerror("错误", error_msg) self.status_var.set(f"错误: {str(e)}") # 更新结果文本框 self.result_text.config(state=tk.NORMAL) self.result_text.insert(tk.END, f"\n错误: {error_msg}\n") self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) def log_column_total_stats(self, column_stats): """记录整列统计结果,并分析1-172范围内的缺失值""" self.logger.info("\n===== 整列值统计结果 =====") # 定义值的范围 (1-172) EXPECTED_VALUES = set(range(1, 173)) for col_num, col_data in column_stats.items(): col_name = col_data['name'] stats = col_data['stats'] if not stats: self.logger.info(f"列 {col_name}: 无有效数据") continue # 按计数值降序排序 sorted_stats = sorted(stats.items(), key=lambda x: x[1], reverse=True) # 记录到日志 self.logger.info(f"\n列 {col_name} 值统计 (按计数降序):") for value, count in sorted_stats: self.logger.info(f" {value}: {count}次") # 分析缺失值 (1-172范围内未出现的值) self.analyze_missing_values(col_name, stats, EXPECTED_VALUES) # 更新UI self.result_text.config(state=tk.NORMAL) self.result_text.insert(tk.END, f"\n列 {col_name} 值统计:\n") for value, count in sorted_stats: self.result_text.insert(tk.END, f" {value}: {count}次\n") self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) def analyze_missing_values(self, col_name, stats, expected_values): """分析并记录1-172范围内缺失的值""" # 提取实际出现的数值 present_values = set() for value_str in stats.keys(): try: # 尝试将值转换为整数 value_int = int(value_str) present_values.add(value_int) except (ValueError, TypeError): # 如果无法转换为整数,跳过 continue # 计算缺失值 missing_values = expected_values - present_values if not missing_values: self.logger.info(f"列 {col_name}: 1-172范围内所有值均已出现") return # 对缺失值排序 sorted_missing = sorted(missing_values) # 记录缺失值信息 self.logger.warning(f"列 {col_name}: 1-172范围内缺失 {len(missing_values)} 个值") # 将缺失值分组显示 missing_groups = self.group_values(sorted_missing) for group in missing_groups: self.logger.info(f" 缺失值: {group}") # 在UI中显示缺失值 self.result_text.config(state=tk.NORMAL) self.result_text.insert(tk.END, f"\n列 {col_name} 缺失值统计 (1-172):\n") self.result_text.insert(tk.END, f" 缺失 {len(missing_values)} 个值\n") for group in missing_groups: self.result_text.insert(tk.END, f" 缺失: {group}\n") self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) def group_values(self, values): """将连续的数字分组显示 (如 1-5, 8, 10-12)""" if not values: return [] groups = [] start = values[0] end = values[0] for i in range(1, len(values)): if values[i] == end + 1: end = values[i] else: if start == end: groups.append(str(start)) else: groups.append(f"{start}-{end}") start = values[i] end = values[i] # 添加最后一组 if start == end: groups.append(str(start)) else: groups.append(f"{start}-{end}") return groups def log_cell_top_stats(self, cell_stats): """功能2: 记录单元格计数排名(取前三)""" self.logger.info("\n===== 单元格计数排名 =====") for col_num, col_data in cell_stats.items(): col_name = col_data['name'] cell_counts = col_data['cell_counts'] if not cell_counts: self.logger.info(f"列 {col_name}: 无有效单元格数据") continue # 按单元格总计数降序排序 sorted_cells = sorted(cell_counts, key=lambda x: x[1], reverse=True)[:3] # 记录到日志 self.logger.info(f"\n列 {col_name} 单元格计数前三:") for rank, (row_idx, count, files) in enumerate(sorted_cells, 1): # 格式化文件列表 file_list = ", ".join(files[:3]) # 只显示前3个文件名 if len(files) > 3: file_list += f" 等{len(files)}个文件" self.logger.info( f" 第{rank}名: 行{row_idx}, 总计数: {count}\n" f" 关联文件: {file_list}" ) # 更新UI self.result_text.config(state=tk.NORMAL) self.result_text.insert(tk.END, f"\n列 {col_name} 单元格计数前三:\n") for rank, (row_idx, count, files) in enumerate(sorted_cells, 1): file_list = ", ".join(files[:3]) if len(files) > 3: file_list += f" 等{len(files)}个文件" self.result_text.insert( tk.END, f" 第{rank}名: 行{row_idx}, 计数: {count}, 文件: {file_list}\n" ) self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) def log_combined_column_stats(self, column_total_stats): """Statistics for combined values across all key columns""" self.logger.info("\n===== 所有关键列合并值统计 =====") # 定义值的范围 (1-172) EXPECTED_VALUES = set(range(1, 173)) # 合并所有列的统计结果 combined_stats = defaultdict(int) for col_data in column_total_stats.values(): stats = col_data['stats'] for value_str, count in stats.items(): try: # 尝试将值转换为整数 value_int = int(value_str) combined_stats[value_int] += count except (ValueError, TypeError): # 如果无法转换为整数,跳过 continue # 按计数值降序排序 sorted_combined = sorted(combined_stats.items(), key=lambda x: x[1], reverse=True) # 记录到日志 self.logger.info("\n所有关键列合并值统计 (按计数降序):") for value, count in sorted_combined: self.logger.info(f" {value}: {count}次") # 分析缺失值 (1-172范围内未出现的值) present_values = set(combined_stats.keys()) missing_values = EXPECTED_VALUES - present_values if not missing_values: self.logger.info("\n所有关键列: 1-172范围内所有值均已出现") else: # 对缺失值排序 sorted_missing = sorted(missing_values) # 记录缺失值信息 self.logger.warning(f"\n所有关键列: 1-172范围内缺失 {len(missing_values)} 个值") # 将缺失值分组显示 missing_groups = self.group_values(sorted_missing) for group in missing_groups: self.logger.info(f" 缺失值: {group}") # 更新UI self.result_text.config(state=tk.NORMAL) self.result_text.insert(tk.END, "\n===== 所有关键列合并值统计 =====") self.result_text.insert(tk.END, "\n值统计 (按计数降序):\n") for value, count in sorted_combined: self.result_text.insert(tk.END, f" {value}: {count}次\n") if missing_values: self.result_text.insert(tk.END, f"\n1-172范围内缺失 {len(missing_values)} 个值:\n") for group in missing_groups: self.result_text.insert(tk.END, f" 缺失: {group}\n") else: self.result_text.insert(tk.END, "\n1-172范围内所有值均已出现\n") self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) def process_stats_mode(self, scl_folder, prefix): """处理统计模式:扫描统计表E列获取SCL文件名""" # 检查输入文件是否存在 input_file = self.input_path_var.get() if not input_file: messagebox.showwarning("警告", "请先选择统计表") self.logger.warning("未选择统计表") return if not os.path.exists(input_file): messagebox.showerror("错误", f"统计表文件不存在: {input_file}") self.logger.error(f"统计表文件不存在: {input_file}") return # 使用openpyxl加载工作簿(保留格式) wb = openpyxl.load_workbook(input_file) sheet = wb.active self.logger.info(f"工作簿加载成功, 工作表: {sheet.title}") # 扫描E列(第5列) total_rows = sheet.max_row processed_count = 0 found_files = 0 problem_files = 0 self.logger.info(f"开始扫描E列, 总行数: {total_rows}") start_time = time.time() # 创建列号到列字母的映射(用于日志) column_letter_map = self.create_column_letter_map() # 初始化目标列统计字典 target_columns = { 'W': 23, 'AD': 30, 'AK': 37, 'AS': 45, 'BA': 53, 'BH': 60, 'BO': 67, 'BV': 74, 'CG': 85 } # 初始化整列统计字典 column_total_stats = {} # 初始化单元格统计字典 cell_stats = {} # 初始化整列统计字典 total_stats = {} # 初始化目标列统计 for col_name, col_num in target_columns.items(): column_total_stats[col_num] = { 'name': col_name, 'stats': defaultdict(int) # 值: 总计数 } cell_stats[col_num] = { 'name': col_name, 'cell_counts': [] # 存储(行号, 单元格总计数, 文件列表) } for row_idx in range(1, total_rows + 1): # 更新进度 progress = (row_idx / total_rows) * 100 self.progress_var.set(progress) self.progress_label.config(text=f"{progress:.1f}%") self.status_var.set(f"处理行: {row_idx}/{total_rows}") self.root.update() cell = sheet.cell(row=row_idx, column=5) cell_value = str(cell.value) if cell.value else "" # 检查是否包含前缀的文件名 if prefix in cell_value: # 改进的正则表达式:匹配包含空格的文件名 # 匹配模式:以prefix开头,后跟任意字符(包括空格),直到文件扩展名 pattern = re.compile( fr'{prefix}[^\s]*\s*[^\s]*\.(?:xlsx|xls|xlsm)', re.IGNORECASE ) file_names = pattern.findall(cell_value) self.logger.info(f"行 {row_idx}: 找到文件: {', '.join(file_names)}") result_lines = [] file_has_problems = False # 标记当前行是否有问题文件 for file_name in file_names: # 在SCL文件夹及其子目录中查找文件(保留文件名中的空格) file_path = self.find_single_scl_file(scl_folder, file_name) # 检查文件是否存在 if not file_path or not os.path.exists(file_path): result_lines.append(f"{file_name}: 文件不存在") self.logger.warning(f"文件不存在: {file_name}") # 标记文件不存在的单元格为紫色 self.highlight_cell(sheet, row_idx, 5, "FF800080") file_has_problems = True problem_files += 1 continue # 执行统计处理 results, color_report, missing_data = self.stats_processor.process_file(file_path) # 如果有数据缺失 if missing_data: file_has_problems = True problem_files += 1 result_lines.append(f"{file_name}: 数据缺失!") for item in missing_data: result_lines.append(f" - {item['message']}") self.logger.warning(item['message']) else: result_lines.append(f"{file_name}: 处理完成") # 将结果写入主Excel文件的不同列 for rule_name, result_str in results.items(): target_col = self.stats_processor.RULE_MAPPING.get(rule_name) if target_col: target_cell = sheet.cell(row=row_idx, column=target_col) target_cell.value = result_str found_files += 1 # 处理目标列统计 for col_name, col_num in target_columns.items(): cell = sheet.cell(row=row_idx, column=col_num) cell_value = cell.value # 跳过空值和错误信息 if cell_value is None or (isinstance(cell_value, str) and cell_value.startswith("错误")): continue # 处理单元格值 cell_total = 0 # 记录当前单元格的总计数 cell_lines = [] # 将单元格内容转换为字符串列表 if isinstance(cell_value, str): # 按换行符分割 cell_lines = cell_value.split('\n') elif isinstance(cell_value, (int, float)): # 如果是数字,直接转换为字符串 cell_lines = [str(cell_value)] else: # 其他类型直接跳过 continue # 处理每一行内容 for line in cell_lines: # 跳过无效行(包含"/"符号) if '/' in line: continue # 分割值和计数 parts = line.split(',') if len(parts) < 2: # 尝试其他分隔符 if ':' in line: parts = line.split(':') elif ';' in line: parts = line.split(';') elif ' ' in line: parts = line.split(' ') # 如果仍然无法分割,跳过 if len(parts) < 2: continue try: # 提取值和计数 value = parts[0].strip() count = int(parts[1].strip()) # 更新整列统计 if value not in column_total_stats[col_num]['stats']: column_total_stats[col_num]['stats'][value] = 0 column_total_stats[col_num]['stats'][value] += count cell_total += count except (ValueError, IndexError) as e: # 记录解析错误 self.logger.warning( f"行 {row_idx} 列 {col_name} 无法解析值: {line} - 错误: {str(e)}" ) # 如果单元格有有效计数,记录到单元格统计 if cell_total > 0: if 'cell_counts' not in cell_stats[col_num]: cell_stats[col_num]['cell_counts'] = [] cell_stats[col_num]['cell_counts'].append( (row_idx, cell_total, file_names.copy()) ) # 如果该行有文件存在问题,将E列单元格标红 if file_has_problems: self.highlight_cell(sheet, row_idx, 5) self.logger.info(f"行 {row_idx} E列单元格标记为红色(存在问题)") # 更新结果文本框 self.result_text.config(state=tk.NORMAL) self.result_text.insert( tk.END, f"行 {row_idx} 处理结果:\n" + "\n".join(result_lines) + "\n\n" ) self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) processed_count += 1 # 保存修改后的Excel文件 output_path = input_file.replace(".xlsx", "_processed.xlsx") wb.save(output_path) self.logger.info(f"结果已保存到: {output_path}") # 记录关键列统计结果到日志和UI self.log_column_total_stats(column_total_stats) # 功能1统计 self.log_cell_top_stats(cell_stats) # 功能2统计 self.log_combined_column_stats(column_total_stats) # 总计数统计 elapsed_time = time.time() - start_time status_msg = f"统计处理完成! 处理了 {processed_count} 个文件项, 耗时 {elapsed_time:.2f} 秒" if problem_files > 0: status_msg += f", {problem_files} 个文件存在问题" self.status_var.set(status_msg) self.logger.info(status_msg) # 更新结果文本框 self.result_text.config(state=tk.NORMAL) self.result_text.insert( tk.END, f"\n{status_msg}\n" f"结果已保存到: {output_path}\n" ) self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) messagebox.showinfo("完成", status_msg) def process_release_mode(self, scl_folder, prefix): """处理 Release 模式:使用 ReleaseSCLProcessor 进行统计""" # 检查输入文件是否存在 input_file = self.input_path_var.get() if not input_file: messagebox.showwarning("警告", "请先选择统计表") self.logger.warning("未选择统计表") return if not os.path.exists(input_file): messagebox.showerror("错误", f"统计表文件不存在: {input_file}") self.logger.error(f"统计表文件不存在: {input_file}") return # 使用openpyxl加载工作簿(保留格式) wb = openpyxl.load_workbook(input_file) sheet = wb.active self.logger.info(f"工作簿加载成功, 工作表: {sheet.title}") # 扫描E列(第5列) total_rows = sheet.max_row processed_count = 0 found_files = 0 problem_files = 0 self.logger.info(f"开始扫描E列, 总行数: {total_rows}") start_time = time.time() # 创建列号到列字母的映射(用于日志) column_letter_map = self.create_column_letter_map() # 定义 Release 模式的目标列映射 release_target_columns = { 'W': 23, 'AD': 30, 'AK': 37, 'AS': 45, 'BA': 53, 'BH': 60, 'BO': 67, 'BV': 74, 'CG': 85 } # 初始化整列统计字典 column_total_stats = {} # 初始化单元格统计字典 cell_stats = {} # 初始化目标列统计 for col_name, col_num in release_target_columns.items(): column_total_stats[col_num] = { 'name': col_name, 'stats': defaultdict(int) # 值: 总计数 } cell_stats[col_num] = { 'name': col_name, 'cell_counts': [] # 存储(行号, 单元格总计数, 文件列表) } for row_idx in range(1, total_rows + 1): # 更新进度 progress = (row_idx / total_rows) * 100 self.progress_var.set(progress) self.progress_label.config(text=f"{progress:.1f}%") self.status_var.set(f"处理行: {row_idx}/{total_rows}") self.root.update() cell = sheet.cell(row=row_idx, column=5) cell_value = str(cell.value) if cell.value else "" # 检查是否包含前缀的文件名 if prefix in cell_value: # 改进的正则表达式:匹配包含空格的文件名 pattern = re.compile( fr'{prefix}[^\s]*\s*[^\s]*\.(?:xlsx|xls|xlsm)', re.IGNORECASE ) file_names = pattern.findall(cell_value) self.logger.info(f"行 {row_idx}: 找到文件: {', '.join(file_names)}") result_lines = [] file_has_problems = False # 标记当前行是否有问题文件 for file_name in file_names: # 在SCL文件夹及其子目录中查找文件 file_path = self.find_single_scl_file(scl_folder, file_name) # 检查文件是否存在 if not file_path or not os.path.exists(file_path): result_lines.append(f"{file_name}: 文件不存在") self.logger.warning(f"文件不存在: {file_name}") # 标记文件不存在的单元格为紫色 self.highlight_cell(sheet, row_idx, 5, "FF800080") file_has_problems = True problem_files += 1 continue try: # 使用 ReleaseSCLProcessor 处理文件 results, color_report, missing_data = self.release_processor.process_file(file_path) # 如果有数据缺失 if missing_data: file_has_problems = True problem_files += 1 result_lines.append(f"{file_name}: 数据缺失!") for item in missing_data: result_lines.append(f" - {item['message']}") self.logger.warning(item['message']) else: result_lines.append(f"{file_name}: 处理完成") # 将结果写入主Excel文件的不同列 for rule_name, result_str in results.items(): target_col = self.release_processor.RULE_MAPPING.get(rule_name) if target_col: target_cell = sheet.cell(row=row_idx, column=target_col) target_cell.value = result_str except Exception as e: error_msg = f"处理文件 {file_name} 时出错: {str(e)}" self.logger.exception(error_msg) result_lines.append(error_msg) file_has_problems = True problem_files += 1 # 标记出错的单元格为红色 self.highlight_cell(sheet, row_idx, 5) continue found_files += 1 # 处理目标列统计 for col_name, col_num in release_target_columns.items(): cell = sheet.cell(row=row_idx, column=col_num) cell_value = cell.value # 跳过空值和错误信息 if cell_value is None or (isinstance(cell_value, str) and cell_value.startswith("错误")): continue # 处理单元格值 cell_total = 0 # 记录当前单元格的总计数 cell_lines = [] # 将单元格内容转换为字符串列表 if isinstance(cell_value, str): # 按换行符分割 cell_lines = cell_value.split('\n') elif isinstance(cell_value, (int, float)): # 如果是数字,直接转换为字符串 cell_lines = [str(cell_value)] else: # 其他类型直接跳过 continue # 处理每一行内容 for line in cell_lines: # 跳过无效行(包含"/"符号) if '/' in line: continue # 分割值和计数 parts = line.split(',') if len(parts) < 2: # 尝试其他分隔符 if ':' in line: parts = line.split(':') elif ';' in line: parts = line.split(';') elif ' ' in line: parts = line.split(' ') # 如果仍然无法分割,跳过 if len(parts) < 2: continue try: # 提取值和计数 value = parts[0].strip() count = int(parts[1].strip()) # 更新整列统计 if value not in column_total_stats[col_num]['stats']: column_total_stats[col_num]['stats'][value] = 0 column_total_stats[col_num]['stats'][value] += count cell_total += count except (ValueError, IndexError) as e: # 记录解析错误 self.logger.warning( f"行 {row_idx} 列 {col_name} 无法解析值: {line} - 错误: {str(e)}" ) # 如果单元格有有效计数,记录到单元格统计 if cell_total > 0: if 'cell_counts' not in cell_stats[col_num]: cell_stats[col_num]['cell_counts'] = [] cell_stats[col_num]['cell_counts'].append( (row_idx, cell_total, file_names.copy()) ) # 如果该行有文件存在问题,将E列单元格标红 if file_has_problems: self.highlight_cell(sheet, row_idx, 5) self.logger.info(f"行 {row_idx} E列单元格标记为红色(存在问题)") # 更新结果文本框 self.result_text.config(state=tk.NORMAL) self.result_text.insert( tk.END, f"行 {row_idx} 处理结果:\n" + "\n".join(result_lines) + "\n\n" ) self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) processed_count += 1 # 保存修改后的Excel文件 output_path = input_file.replace(".xlsx", "_release_processed.xlsx") wb.save(output_path) self.logger.info(f"结果已保存到: {output_path}") # 记录关键列统计结果到日志和UI self.log_column_total_stats(column_total_stats) # 整列统计 self.log_cell_top_stats(cell_stats) # 单元格计数排名 elapsed_time = time.time() - start_time status_msg = f"Release处理完成! 处理了 {processed_count} 个文件项, 耗时 {elapsed_time:.2f} 秒" if problem_files > 0: status_msg += f", {problem_files} 个文件存在问题" self.status_var.set(status_msg) self.logger.info(status_msg) # 更新结果文本框 self.result_text.config(state=tk.NORMAL) self.result_text.insert( tk.END, f"\n{status_msg}\n" f"结果已保存到: {output_path}\n" ) self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) messagebox.showinfo("完成", status_msg) def process_empty_check_mode(self, scl_folder, prefix): """处理SCL格式检查模式:直接扫描文件夹中的所有SCL文件""" # 检查CheckSheet路径 checksheet_path = self.checksheet_path_var.get() if not checksheet_path: messagebox.showwarning("警告", "请先选择CheckSheet路径") self.logger.warning("未选择CheckSheet路径") return if not os.path.exists(checksheet_path): messagebox.showerror("错误", f"CheckSheet文件不存在: {checksheet_path}") self.logger.error(f"CheckSheet文件不存在: {checksheet_path}") return # 创建输出目录结构 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") output_dir = os.path.join(scl_folder, f"SCL_Check_Results_{timestamp}") marked_files_dir = os.path.join(output_dir, "MarkedFiles") reports_dir = os.path.join(output_dir, "Reports") # 确保目录存在 os.makedirs(marked_files_dir, exist_ok=True) os.makedirs(reports_dir, exist_ok=True) self.logger.info(f"创建输出目录: {output_dir}") self.logger.info(f"标记文件保存目录: {marked_files_dir}") self.logger.info(f"报告保存目录: {reports_dir}") # 查找所有SCL文件 scl_files = self.find_scl_files(scl_folder, prefix) if not scl_files: messagebox.showinfo("信息", f"在 {scl_folder} 中未找到以 {prefix} 开头的SCL文件") self.logger.info(f"未找到以 {prefix} 开头的SCL文件") return # 开始处理 total_files = len(scl_files) processed_count = 0 problem_files = 0 self.logger.info(f"找到 {total_files} 个SCL文件, 开始处理...") start_time = time.time() # 创建结果报告文件 report_filename = f"SCL_Format_Check_Report_{timestamp}.txt" report_path = os.path.join(reports_dir, report_filename) report_content = [ f"SCL格式检查报告 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", f"检查目录: {scl_folder}", f"文件前缀: {prefix}", f"文件总数: {total_files}", "=" * 60, "" ] # 处理每个SCL文件 for idx, scl_file in enumerate(scl_files): # 更新进度 progress = ((idx + 1) / total_files) * 100 self.progress_var.set(progress) self.progress_label.config(text=f"{progress:.1f}%") self.status_var.set(f"正在处理: {os.path.basename(scl_file)} ({idx+1}/{total_files})") self.root.update() # 执行空单元格检查 missing_data, marked_file_path = self.empty_cell_detector.detect_empty_cells( scl_file, checksheet_path ) # 记录结果 result_lines = [] result_lines.append(f"文件: {os.path.basename(scl_file)}") if missing_data: problem_files += 1 result_lines.append("状态: 发现问题!") for item in missing_data: result_lines.append(f" - {item['message']}") self.logger.warning(item['message']) # 添加标记文件路径信息 if marked_file_path: # 将标记文件移动到专门目录 target_path = os.path.join( marked_files_dir, os.path.basename(marked_file_path) ) # 确保目标目录存在 os.makedirs(os.path.dirname(target_path), exist_ok=True) # 移动文件 try: shutil.move(marked_file_path, target_path) marked_file_path = target_path result_lines.append(f"标记文件已保存到: {os.path.relpath(target_path, scl_folder)}") self.logger.info(f"标记文件已移动到: {target_path}") except Exception as e: error_msg = f"移动标记文件失败: {str(e)}" result_lines.append(error_msg) self.logger.error(error_msg) else: result_lines.append("状态: 无问题") # 添加到报告 report_content.extend(result_lines) report_content.append("") # 空行分隔 # 更新结果文本框 self.result_text.config(state=tk.NORMAL) self.result_text.insert(tk.END, "\n".join(result_lines) + "\n\n") self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) processed_count += 1 # 添加总结信息到报告 report_content.extend([ "=" * 60, f"处理总结:", f"总文件数: {total_files}", f"已处理文件数: {processed_count}", f"问题文件数: {problem_files}", f"处理耗时: {time.time() - start_time:.2f} 秒", f"输出目录: {output_dir}", f"标记文件目录: {marked_files_dir}", f"报告文件: {report_path}" ]) # 保存报告文件 with open(report_path, 'w', encoding='utf-8') as f: f.write("\n".join(report_content)) elapsed_time = time.time() - start_time status_msg = f"SCL格式检查完成! 处理了 {processed_count} 个文件, 耗时 {elapsed_time:.2f} 秒" if problem_files > 0: status_msg += f", {problem_files} 个文件发现问题" status_msg += f"\n所有输出文件已保存到: {output_dir}" self.status_var.set(status_msg) self.logger.info(status_msg) # 更新结果文本框 self.result_text.config(state=tk.NORMAL) self.result_text.insert( tk.END, f"\n{status_msg}\n" f"检查报告已保存到: {report_path}\n" f"标记文件已保存到: {marked_files_dir}\n" ) self.result_text.see(tk.END) self.result_text.config(state=tk.DISABLED) messagebox.showinfo("完成", f"{status_msg}\n输出目录: {output_dir}") def process_excel_comparison(self): """执行Excel文件比较""" try: before_folder = self.before_folder_var.get() after_folder = self.after_folder_var.get() similarity_threshold = self.similarity_var.get() if not before_folder or not after_folder: messagebox.showwarning("警告", "请选择Before和After文件夹") self.logger.warning("未选择Before或After文件夹") return # 检查文件夹是否存在 if not os.path.exists(before_folder): messagebox.showerror("错误", f"Before文件夹不存在: {before_folder}") self.logger.error(f"Before文件夹不存在: {before_folder}") return if not os.path.exists(after_folder): messagebox.showerror("错误", f"After文件夹不存在: {after_folder}") self.logger.error(f"After文件夹不存在: {after_folder}") return # 创建比较窗口 compare_root = tk.Toplevel(self.root) compare_root.title("Excel文件比较工具") compare_root.geometry("1000x700") # 创建比较工具实例 comparator = EnhancedExcelComparatorApp(compare_root) comparator.before_folder_var.set(before_folder) comparator.after_folder_var.set(after_folder) comparator.similarity_var.set(similarity_threshold) # 设置进度回调 comparator.progress_callback = self.update_progress # 记录 self.logger.info("Excel比较窗口已打开") except Exception as e: error_msg = f"打开Excel比较工具失败: {str(e)}" self.logger.exception(error_msg) messagebox.showerror("错误", error_msg) self.status_var.set(f"错误: {str(e)}") def update_progress(self, value, message): """更新进度条和状态信息""" self.progress_var.set(value) self.progress_label.config(text=f"{value:.1f}%") self.status_var.set(message) self.root.update() def find_single_scl_file(self, folder, filename): """ 在指定目录及其子目录中查找单个文件(支持文件名空格处理) 当存在多个同名文件时,优先选择日期最近的目录中的文件 :param folder: 要搜索的根目录 :param filename: 要查找的文件名(可能包含空格) :return: 找到的文件路径,如果未找到则返回None """ self.logger.info(f"开始查找文件: {filename} 在目录: {folder}") # 存储找到的所有文件信息 found_files = [] # 遍历目录及其所有子目录 for root, _, files in os.walk(folder): for file in files: # 检查文件名是否完全匹配(包括空格) if file == filename: full_path = os.path.join(root, file) # 从路径中提取日期信息 folder_date = self.extract_date_from_path(root) mod_time = os.path.getmtime(full_path) # 存储文件信息 file_info = { 'path': full_path, 'folder_date': folder_date, 'mod_time': mod_time, 'folder_path': root } found_files.append(file_info) self.logger.debug(f"找到匹配文件: {full_path} (日期: {folder_date})") # 处理找到的文件 if not found_files: self.logger.warning(f"未找到文件: {filename}") return None # 如果只有一个文件,直接返回 if len(found_files) == 1: self.logger.info(f"找到唯一文件: {found_files[0]['path']}") return found_files[0]['path'] # 多个同名文件,选择日期最近的 self.logger.info(f"找到 {len(found_files)} 个同名文件,将选择日期最近的") # 过滤出有有效日期的文件 valid_files = [f for f in found_files if f['folder_date'] is not None] if not valid_files: # 所有文件都没有有效日期,选择修改时间最近的 latest_file = max(found_files, key=lambda x: x['mod_time']) self.logger.warning(f"所有文件都没有有效日期,选择最近修改的: {latest_file['path']}") return latest_file['path'] # 按日期排序(最近的在前) sorted_files = sorted( valid_files, key=lambda x: x['folder_date'], reverse=True ) # 选择日期最近的 selected_file = sorted_files[0] self.logger.info(f"选择日期最近的目录中的文件: {selected_file['folder_date']} -> {selected_file['path']}") # 记录被忽略的文件 for i, file in enumerate(sorted_files[1:], 1): self.logger.debug(f"忽略文件 {i}: {file['path']} (日期: {file['folder_date']})") return selected_file['path'] def find_scl_files(self, folder, prefix): """查找指定文件夹中以指定前缀开头的所有SCL文件,确保同名文件选择日期最近的目录""" self.logger.info(f"在 {folder} 中查找以 {prefix} 开头的文件") # 支持的Excel文件扩展名 excel_extensions = ('.xlsx', '.xls', '.xlsm') # 存储文件信息:{文件名: [文件信息]} file_dict = defaultdict(list) # 存储最终选择的文件 selected_files = [] # 遍历文件夹 for root, _, files in os.walk(folder): # 从路径中提取日期信息(四位日期格式) folder_date = self.extract_date_from_path(root) for file in files: normalized_name = file.strip() # 检查文件扩展名和前缀 if not normalized_name.lower().endswith(excel_extensions): continue if not normalized_name.startswith(prefix): continue full_path = os.path.join(root, file) mod_time = os.path.getmtime(full_path) # 存储文件信息 file_info = { 'path': full_path, 'folder_date': folder_date, 'mod_time': mod_time, 'folder_path': root } file_dict[normalized_name].append(file_info) self.logger.debug(f"找到文件: {normalized_name} 在 {root} (日期: {folder_date})") # 处理同名文件:优先选择日期最近的目录 for filename, files in file_dict.items(): if len(files) == 1: # 只有一个文件,直接选择 selected_files.append(files[0]) self.logger.info(f"文件 {filename} 只有唯一版本: {files[0]['path']}") else: # 找到日期最近的文件 valid_files = [f for f in files if f['folder_date'] is not None] if not valid_files: # 所有文件都没有日期,选择修改时间最近的 latest_file = max(files, key=lambda x: x['mod_time']) selected_files.append(latest_file) self.logger.warning(f"同名文件 {filename} 没有日期信息,选择最近修改的: {latest_file['path']}") else: # 按日期排序(从近到远) sorted_files = sorted( valid_files, key=lambda x: x['folder_date'], reverse=True ) # 选择日期最近的 selected_file = sorted_files[0] selected_files.append(selected_file) # 记录选择结果 self.logger.info(f"同名文件 {filename} 选择最近日期的目录: {selected_file['folder_date']} -> {selected_file['path']}") # 记录被忽略的文件 for f in sorted_files[1:]: self.logger.debug(f"忽略同名文件: {f['path']} (日期: {f['folder_date']})") # 按日期排序所有选择的文件 final_sorted_files = sorted( selected_files, key=lambda x: (x['folder_date'] if x['folder_date'] else "", -x['mod_time']), reverse=True ) # 提取文件路径 scl_files = [f['path'] for f in final_sorted_files] # 记录最终结果 self.logger.info(f"找到 {len(scl_files)} 个文件:") for i, path in enumerate(scl_files, 1): self.logger.info(f"{i}. {path}") return scl_files def extract_date_from_path(self, path): """ 从文件路径中提取四位日期信息 (MMDD格式) 返回日期字符串或None """ # 分割路径为各个部分 path_parts = path.split(os.sep) # 尝试从路径的每个部分提取四位日期 for part in reversed(path_parts): # 使用正则表达式提取四位数字 match = re.search(r'(\d{4})', part) if match: date_str = match.group(1) # 验证是否为有效日期 (MMDD) month = int(date_str[:2]) day = int(date_str[2:4]) if 1 <= month <= 12 and 1 <= day <= 31: return date_str return None def view_log(self): """查看日志""" log_window = tk.Toplevel(self.root) log_window.title("处理日志") log_window.geometry("800x600") log_frame = ttk.Frame(log_window, padding="10") log_frame.pack(fill=tk.BOTH, expand=True) # 日志文本框 log_text = scrolledtext.ScrolledText( log_frame, wrap=tk.WORD, height=30 ) log_text.pack(fill=tk.BOTH, expand=True) # 读取日志文件 if self.current_log_file and os.path.exists(self.current_log_file): try: with open(self.current_log_file, 'r', encoding='utf-8') as f: log_content = f.read() log_text.insert(tk.END, log_content) except Exception as e: log_text.insert(tk.END, f"无法读取日志文件: {str(e)}") else: log_text.insert(tk.END, "日志文件不存在或尚未创建") # 设置为只读 log_text.config(state=tk.DISABLED) # 添加刷新按钮 refresh_btn = ttk.Button(log_frame, text="刷新日志", command=lambda: self.refresh_log(log_text)) refresh_btn.pack(pady=5) self.logger.info("日志查看窗口已打开") def refresh_log(self, log_text): """刷新日志内容""" log_text.config(state=tk.NORMAL) log_text.delete(1.0, tk.END) if self.current_log_file and os.path.exists(self.current_log_file): try: with open(self.current_log_file, 'r', encoding='utf-8') as f: log_content = f.read() log_text.insert(tk.END, log_content) except Exception as e: log_text.insert(tk.END, f"刷新日志失败: {str(e)}") else: log_text.insert(tk.END, "日志文件不存在或尚未创建") log_text.config(state=tk.DISABLED) log_text.see(tk.END) self.logger.info("日志已刷新") def export_config(self): """导出配置到文件""" config = { "prefix": self.prefix_var.get(), "log_level": self.log_level_var.get(), "operation_mode": self.operation_mode.get(), "checksheet_path": self.checksheet_path_var.get(), "scl_folder": self.scl_folder_var.get(), "input_path": self.input_path_var.get() } file_path = filedialog.asksaveasfilename( defaultextension=".json", filetypes=[("JSON 文件", "*.json"), ("所有文件", "*.*")] ) if file_path: try: with open(file_path, 'w', encoding='utf-8') as f: f.write(str(config)) messagebox.showinfo("成功", f"配置已导出到: {file_path}") self.logger.info(f"配置已导出到: {file_path}") except Exception as e: messagebox.showerror("错误", f"导出配置失败: {str(e)}") self.logger.error(f"导出配置失败: {str(e)}") def load_config(self): """从文件加载配置""" file_path = filedialog.askopenfilename( filetypes=[("JSON 文件", "*.json"), ("所有文件", "*.*")] ) if file_path: try: with open(file_path, 'r', encoding='utf-8') as f: config = eval(f.read()) self.prefix_var.set(config.get("prefix", "SCL_")) self.log_level_var.set(config.get("log_level", "INFO")) self.operation_mode.set(config.get("operation_mode", "stats")) self.checksheet_path_var.set(config.get("checksheet_path", "")) self.scl_folder_var.set(config.get("scl_folder", "")) self.input_path_var.set(config.get("input_path", "")) # 更新UI显示 self.toggle_config_fields() self.change_log_level() messagebox.showinfo("成功", "配置已加载") self.logger.info(f"配置已从 {file_path} 加载") except Exception as e: messagebox.showerror("错误", f"加载配置失败: {str(e)}") self.logger.error(f"加载配置失败: {str(e)}")
主程序入口
if name == “main”:
root = tk.Tk()
app = SCLMultiProcessor(root)
root.mainloop()
现在在主界面上选择文件夹后点击开始处理会弹出第二个窗口,我不需要第二个窗口,把比较结果直接输出到主窗口的处理结果那里就行,不需要第二个窗口
最新发布