去掉Drag a column header

本文介绍了如何在Dev的GridControl中去除"Drag a column header here to group by that column"的提示,并设置控件外观。通过设置OptionViews.ShowGroupPanel为false和调整Column options的属性,可以禁用列头的过滤功能及右键菜单的英文显示。此外,还提供了手工设置和代码编写两种方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GridControl这个第三方控件是VS2005自带的datagridview控件的重写版本。对于一些grid外观,模板列的设置有非常简单的方法.而且控制起来基本和datagridview一样.所以还是比较方便的.把GridContol控件拖到窗体以后,会发现多了两个控件gridcontrol1,gridview1,下面针对这期间使用dev的一些总结写在下面(主要是连接数据库,绑定字段和模板列的设置):

  示例:

  去掉上面的”Drag a column header here to group by that column”

  我们拖动一个gridcontrol控件后,在出现上会出现一下效果:

   他默认的好多地方都是用英文表示出来的,所以我们得用一些相关的属性设置来达到我们实际想要达到的效果.首先就是要去掉上面的一个英文条”Drag a column header here to group by that column”.我们可以通过手工设置和代码编写来实现,以后针对第三方控件的属性都可以用这两种方法来实现.手工设置:点击左下角的”Run Designer”按钮. 

  这样我们就进入了Dev的设计器(所有的对于控件的控制都可以在这里设置).然后点击左边的Main选项卡中的Views项.有边栏目里会出现N多属性,我们找到OptionViews,展开它,然后将里面的ShowGroupPanel属性设成false就OK了.代码编写:

  我们可以直接在构造函数或者页面的打开事件中写入代码:

gridView1.OptionsView.ShowGroupPanel = false;

  两种方法可以达到同样的效果.

  设置外观

  接下来我们来设置它的外观.Dev给我们提供了很多外观的模板,这样使得我们不用在通过复杂的代码来设置他的外观,我们直接用手工设置就可以完成了!点击Dev设计器中左边的Appearance选项卡的Style Schemes项:

  通过在里面设置外观,然后点击右小角的Apply按钮

import pandas as pd import tkinter as tk from tkinter import ttk, messagebox, filedialog import os import json import threading import openpyxl from openpyxl.utils.dataframe import dataframe_to_rows from tkinter.font import Font class ScrollableFrame(ttk.Frame): """自定义可滚动框架实现""" def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) # 创建Canvas和滚动条 self.canvas = tk.Canvas(self) self.scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview) self.scrollable_frame = ttk.Frame(self.canvas) # 配置Canvas self.canvas.configure(yscrollcommand=self.scrollbar.set) self.canvas_frame = self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw") # 布局 self.canvas.pack(side="left", fill="both", expand=True) self.scrollbar.pack(side="right", fill="y") # 绑定事件 self.scrollable_frame.bind("<Configure>", self.on_frame_configure) self.canvas.bind("<Configure>", self.on_canvas_configure) self.canvas.bind_all("<MouseWheel>", self.on_mousewheel) def on_frame_configure(self, event): """当内部框架大小改变时更新滚动区域""" self.canvas.configure(scrollregion=self.canvas.bbox("all")) def on_canvas_configure(self, event): """当Canvas大小改变时调整内部框架宽度""" self.canvas.itemconfig(self.canvas_frame, width=event.width) def on_mousewheel(self, event): """鼠标滚轮滚动支持""" self.canvas.yview_scroll(int(-1*(event.delta/120)), "units") class ExcelControlPanel: def __init__(self, master): self.master = master master.title("功能点确认系统") master.geometry("1280x800") master.configure(bg="#f0f2f5") # 设置全局样式 self.set_styles() # 加载配置 self.config = self.load_config() # 初始化多列确认配置 self.confirmation_columns = self.config.get("confirmation_columns", []) # 创建界面元素 self.create_widgets() # 初始化数据 self.excel_path = "" self.df = None self.check_vars = {} # 存储每个功能点的复选框变量,key为item_id self.current_sheet = "" self.header_row = 0 # 启用列拖动 self.enable_column_dragging() def set_styles(self): """设置全局样式和字体""" style = ttk.Style() style.theme_use('clam') # 自定义字体 self.title_font = Font(family="Microsoft YaHei", size=16, weight="bold") self.subtitle_font = Font(family="Microsoft YaHei", size=12) self.normal_font = Font(family="Microsoft YaHei", size=10) # 配置样式 style.configure("TFrame", background="#f0f2f5") style.configure("TLabel", font=self.normal_font, background="#f0f2f5", foreground="#333") style.configure("TButton", font=self.normal_font, padding=8) style.configure("Treeview.Heading", font=self.subtitle_font, background="#4a76b5", foreground="white") style.configure("Treeview", font=self.normal_font, rowheight=30, background="white", fieldbackground="white") style.configure("Title.TLabel", font=self.title_font, background="#4a76b5", foreground="white", padding=10) style.configure("Status.TLabel", font=self.normal_font, background="#333", foreground="#fff", padding=5) style.configure("Card.TFrame", background="white", borderwidth=0, relief="solid", padding=10, bordercolor="#e1e4e8", borderradius=8) style.configure("Card.TLabelframe", background="white", borderwidth=1, relief="solid", padding=10, bordercolor="#e1e4e8", borderradius=8) style.configure("Card.TLabelframe.Label", font=self.subtitle_font, foreground="#2c3e50", background="white") # 按钮样式 style.map("Primary.TButton", background=[("active", "#3a66a5"), ("pressed", "#2a5685")], foreground=[("active", "white"), ("pressed", "white")]) style.configure("Primary.TButton", background="#4a76b5", foreground="white", font=self.subtitle_font, borderwidth=0, borderradius=4) style.map("Success.TButton", background=[("active", "#28a745"), ("pressed", "#218838")], foreground=[("active", "white"), ("pressed", "white")]) style.configure("Success.TButton", background="#28a745", foreground="white", font=self.subtitle_font, borderwidth=0, borderradius=4) style.map("Danger.TButton", background=[("active", "#dc3545"), ("pressed", "#c82333")], foreground=[("active", "white"), ("pressed", "white")]) style.configure("Danger.TButton", background="#dc3545", foreground="white", font=self.subtitle_font, borderwidth=0, borderradius=4) # 复选框样式 style.configure("Custom.TCheckbutton", background="white", font=self.normal_font) # 输入框样式 style.configure("Custom.TEntry", fieldbackground="#f8f9fa", bordercolor="#ced4da") def load_config(self): """加载配置文件""" config_path = "excel_config.json" default_config = { "id_col": "No.", "desc_col": "レビュー観点(CHN)", "status_col": "レビュー結果", "sheet_name": "", "header_row": 9, "last_dir": os.getcwd(), "custom_status": "OK", "confirmation_columns": [] } if os.path.exists(config_path): try: with open(config_path, 'r', encoding='utf-8') as f: config = json.load(f) # 确保所有键都存在 for key in default_config: if key not in config: config[key] = default_config[key] return config except: return default_config return default_config def save_config(self): """保存配置文件""" config_path = "excel_config.json" with open(config_path, 'w', encoding='utf-8') as f: json.dump(self.config, f, ensure_ascii=False, indent=2) def create_widgets(self): """创建现代化界面元素""" # 主容器 main_container = ttk.Frame(self.master, style="Card.TFrame") main_container.pack(fill="both", expand=True, padx=20, pady=20) # 标题栏 title_frame = ttk.Frame(main_container, style="Title.TFrame") title_frame.pack(fill="x", pady=(0, 20)) # 添加内置图标 try: # 创建一个简单的内置图标 self.icon_img = tk.PhotoImage(width=32, height=32) self.icon_img.put("#4a76b5", (0, 0, 32, 32)) icon_label = ttk.Label(title_frame, image=self.icon_img, background="#4a76b5") icon_label.pack(side="left", padx=(15, 10)) except: pass ttk.Label(title_frame, text="功能点确认系统", style="Title.TLabel").pack(side="left", padx=10) # 主内容区域(卡片式布局) content_frame = ttk.Frame(main_container) content_frame.pack(fill="both", expand=True) # 左侧控制面板(卡片) - 可滚动 control_container = ttk.Frame(content_frame, width=350) control_container.pack(side="left", fill="y", padx=(0, 20)) # 创建自定义可滚动框架 scrollable_frame = ScrollableFrame(control_container, width=350) scrollable_frame.pack(fill="both", expand=True) # 获取内部框架 inner_frame = scrollable_frame.scrollable_frame # 美化控制面板 control_card = ttk.LabelFrame(inner_frame, text="控制面板", style="Card.TLabelframe") control_card.pack(fill="both", expand=True, padx=10, pady=10, ipadx=5, ipady=5) # 文件选择区域 file_frame = ttk.LabelFrame(control_card, text="Excel文件设置") file_frame.pack(fill="x", padx=10, pady=(0, 15)) ttk.Label(file_frame, text="Excel文件路径:").pack(anchor="w", pady=(0, 5), padx=10) path_frame = ttk.Frame(file_frame) path_frame.pack(fill="x", pady=5, padx=10) self.path_entry = ttk.Entry(path_frame, width=30, style="Custom.TEntry") self.path_entry.pack(side="left", fill="x", expand=True, padx=(0, 5)) ttk.Button(path_frame, text="浏览", command=self.browse_file, width=8).pack(side="left") ttk.Button(file_frame, text="加载数据", command=self.load_data, style="Primary.TButton").pack(fill="x", pady=10, padx=10) # Sheet选择区域 sheet_frame = ttk.LabelFrame(control_card, text="工作表设置") sheet_frame.pack(fill="x", padx=10, pady=(0, 15)) ttk.Label(sheet_frame, text="当前Sheet:").pack(anchor="w", padx=10, pady=(10, 0)) self.sheet_var = tk.StringVar(value=self.config.get("sheet_name", "未选择")) sheet_display = ttk.Label(sheet_frame, textvariable=self.sheet_var, font=self.subtitle_font) sheet_display.pack(anchor="w", pady=(0, 10), padx=10) ttk.Button(sheet_frame, text="选择工作表", command=self.select_sheet, style="Primary.TButton").pack(fill="x", padx=10, pady=(0, 10)) # 表头行设置 header_frame = ttk.LabelFrame(control_card, text="表头设置") header_frame.pack(fill="x", padx=10, pady=(0, 15)) ttk.Label(header_frame, text="表头所在行号:").pack(anchor="w", padx=10, pady=(10, 0)) self.header_var = tk.IntVar(value=self.config.get("header_row", 9)) ttk.Entry(header_frame, textvariable=self.header_var, width=10, style="Custom.TEntry").pack(anchor="w", pady=5, padx=10) # 列名配置区域 col_frame = ttk.LabelFrame(control_card, text="列名配置") col_frame.pack(fill="x", padx=10, pady=(0, 15)) # ID列 ttk.Label(col_frame, text="ID列名:").pack(anchor="w", padx=10, pady=(10, 0)) self.id_col_var = tk.StringVar(value=self.config["id_col"]) ttk.Entry(col_frame, textvariable=self.id_col_var, style="Custom.TEntry").pack(fill="x", pady=(0, 10), padx=10) # 功能点列 ttk.Label(col_frame, text="功能点列名:").pack(anchor="w", padx=10, pady=(0, 0)) self.desc_col_var = tk.StringVar(value=self.config["desc_col"]) ttk.Entry(col_frame, textvariable=self.desc_col_var, style="Custom.TEntry").pack(fill="x", pady=(0, 10), padx=10) # 状态列 ttk.Label(col_frame, text="状态列名:").pack(anchor="w", padx=10, pady=(0, 0)) self.status_col_var = tk.StringVar(value=self.config["status_col"]) ttk.Entry(col_frame, textvariable=self.status_col_var, style="Custom.TEntry").pack(fill="x", pady=(0, 10), padx=10) # 自定义状态 ttk.Label(col_frame, text="自定义确认状态:").pack(anchor="w", padx=10, pady=(0, 0)) self.custom_status_var = tk.StringVar(value=self.config.get("custom_status", "OK")) ttk.Entry(col_frame, textvariable=self.custom_status_var, style="Custom.TEntry").pack(fill="x", pady=(0, 10), padx=10) # 多列确认设置 multi_col_frame = ttk.LabelFrame(control_card, text="多列确认设置") multi_col_frame.pack(fill="x", padx=10, pady=(0, 15)) # 列选择器 ttk.Label(multi_col_frame, text="选择要确认的列:").pack(anchor="w", padx=10, pady=(10, 0)) col_selector_frame = ttk.Frame(multi_col_frame) col_selector_frame.pack(fill="x", pady=5, padx=10) self.col_selector = ttk.Combobox(col_selector_frame, state="readonly", width=15, style="Custom.TCombobox") self.col_selector.pack(side="left", fill="x", expand=True, padx=(0, 5)) # 添加/移除按钮 ttk.Button(col_selector_frame, text="添加", command=self.add_confirmation_column, width=8).pack(side="left") # 已选列列表 ttk.Label(multi_col_frame, text="已选确认列 (可拖动调整顺序):").pack(anchor="w", padx=10, pady=(10, 0)) self.selected_cols_listbox = tk.Listbox(multi_col_frame, height=3, font=self.normal_font, bg="#f8f9fa", highlightthickness=0) self.selected_cols_listbox.pack(fill="x", pady=5, padx=10) # 加载已配置的确认列 for col in self.confirmation_columns: self.selected_cols_listbox.insert(tk.END, col) # 移除按钮 remove_btn = ttk.Button(multi_col_frame, text="移除选中列", command=self.remove_confirmation_column) remove_btn.pack(fill="x", pady=(0, 10), padx=10) # 操作按钮区域 btn_frame = ttk.Frame(control_card) btn_frame.pack(fill="x", padx=10, pady=10) ttk.Button(btn_frame, text="保存配置", command=self.save_current_config, style="Success.TButton").pack(fill="x", pady=5) ttk.Button(btn_frame, text="确认选中项", command=self.confirm_selected, style="Primary.TButton").pack(fill="x", pady=5) ttk.Button(btn_frame, text="全选", command=self.select_all, style="Primary.TButton").pack(side="left", fill="x", expand=True, padx=(0, 5), pady=5) ttk.Button(btn_frame, text="取消全选", command=self.deselect_all, style="Danger.TButton").pack(side="left", fill="x", expand=True, padx=(5, 0), pady=5) ttk.Button(btn_frame, text="保存到Excel", command=self.save_to_excel, style="Success.TButton").pack(fill="x", pady=5) # 数据显示区域(卡片) data_card = ttk.LabelFrame(content_frame, text="功能点列表", style="Card.TLabelframe") data_card.pack(side="right", fill="both", expand=True) # 创建带滚动条的表格 columns = ("选择", "ID", "功能点", "状态") self.tree = ttk.Treeview(data_card, columns=columns, show="headings", height=20) vsb = ttk.Scrollbar(data_card, orient="vertical", command=self.tree.yview) hsb = ttk.Scrollbar(data_card, orient="horizontal", command=self.tree.xview) self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set) # 添加分割条和详情文本框 paned_window = tk.PanedWindow(data_card, orient=tk.VERTICAL, sashrelief=tk.RAISED, sashwidth=4) paned_window.pack(fill="both", expand=True, padx=5, pady=5) # 将Treeview放入PanedWindow的上部分 tree_frame = ttk.Frame(paned_window) paned_window.add(tree_frame) self.tree.pack(in_=tree_frame, side="top", fill="both", expand=True) vsb.pack(in_=tree_frame, side="right", fill="y", padx=(0, 5), pady=5) hsb.pack(in_=tree_frame, side="bottom", fill="x", padx=5, pady=(0, 5)) # 配置列 col_widths = {"选择": 50, "ID": 120, "功能点": 600, "状态": 120} for col in columns: self.tree.heading(col, text=col, anchor="w") self.tree.column(col, width=col_widths[col], minwidth=50, stretch=tk.YES if col == "功能点" else tk.NO) # 添加标签样式 self.tree.tag_configure("confirmed", background="#d4edda") self.tree.tag_configure("pending", background="#f8d7da") # 绑定列调整事件 self.tree.bind("<Configure>", self.adjust_columns) # 添加详情文本框 detail_frame = ttk.Frame(paned_window, height=100) paned_window.add(detail_frame) ttk.Label(detail_frame, text="功能点详情:").pack(anchor="w", padx=5, pady=5) self.detail_text = tk.Text(detail_frame, wrap="word", font=self.normal_font, height=5) scroll_detail = ttk.Scrollbar(detail_frame, command=self.detail_text.yview) self.detail_text.config(yscrollcommand=scroll_detail.set) self.detail_text.pack(side="left", fill="both", expand=True, padx=5, pady=5) scroll_detail.pack(side="right", fill="y", padx=(0, 5), pady=5) self.detail_text.config(state="disabled") # 绑定Treeview选择事件 self.tree.bind("<<TreeviewSelect>>", self.on_tree_select) # 状态栏 self.status_var = tk.StringVar() self.status_var.set("就绪 - 请选择Excel文件开始") status_bar = ttk.Label(self.master, textvariable=self.status_var, style="Status.TLabel") status_bar.pack(side="bottom", fill="x") def on_tree_select(self, event): """当Treeview中选中行时,显示功能点详情""" selected_items = self.tree.selection() if not selected_items: return item = selected_items[0] # 获取功能点描述,在第三列(索引2) values = self.tree.item(item, "values") if len(values) >= 3: desc = values[2] self.detail_text.config(state="normal") self.detail_text.delete(1.0, tk.END) self.detail_text.insert(tk.END, desc) self.detail_text.config(state="disabled") def enable_column_dragging(self): """启用列拖动功能""" def on_header_click(event): # 记录开始拖动的列 region = self.tree.identify("region", event.x, event.y) if region == "heading": self.drag_start_col = self.tree.identify_column(event.x) def on_header_drag(event): # 处理拖动中的列 if hasattr(self, 'drag_start_col'): region = self.tree.identify("region", event.x, event.y) if region == "heading": end_col = self.tree.identify_column(event.x) if end_col != self.drag_start_col: # 移动列 self.move_column(self.drag_start_col, end_col) self.drag_start_col = end_col def on_header_release(event): # 结束拖动 if hasattr(self, 'drag_start_col'): del self.drag_start_col # 绑定事件 self.tree.bind("<ButtonPress-1>", on_header_click) self.tree.bind("<B1-Motion>", on_header_drag) self.tree.bind("<ButtonRelease-1>", on_header_release) def move_column(self, from_col, to_col): """移动列位置""" # 获取当前列顺序 columns = list(self.tree["columns"]) # 转换为索引 from_idx = int(from_col.replace("#", "")) - 1 to_idx = int(to_col.replace("#", "")) - 1 # 移动列 if from_idx < len(columns) and to_idx < len(columns): col = columns.pop(from_idx) columns.insert(to_idx, col) # 更新列顺序 self.tree["columns"] = columns # 重新配置列 for i, col in enumerate(columns): self.tree.heading(col, text=col) self.tree.column(col, anchor="w") # 调整列宽 self.adjust_columns(None) def adjust_columns(self, event): """根据窗口大小自动调整列宽""" if not self.tree.winfo_exists(): return width = self.tree.winfo_width() if width < 100: # 防止宽度过小 return # 设置列宽比例:选择 5%,ID 15%,功能点 70%,状态 10% self.tree.column("选择", width=int(width * 0.05)) self.tree.column("ID", width=int(width * 0.15)) self.tree.column("功能点", width=int(width * 0.7)) self.tree.column("状态", width=int(width * 0.1)) # 调整多列确认的列宽 if self.confirmation_columns: for col in self.confirmation_columns: self.tree.column(col, width=int(width * 0.1)) def add_confirmation_column(self): """添加确认列""" col = self.col_selector.get() if col and col not in self.confirmation_columns: self.confirmation_columns.append(col) self.selected_cols_listbox.insert(tk.END, col) # 更新Treeview列 self.update_treeview_columns() def update_treeview_columns(self): """更新Treeview列以显示确认列""" # 构建列列表 columns = ["选择", "ID", "功能点", "状态"] + self.confirmation_columns # 重新配置Treeview self.tree.configure(columns=columns) self.tree["show"] = "headings" # 设置列标题 for col in columns: self.tree.heading(col, text=col) # 设置最小宽度和拉伸属性 if col == "功能点": self.tree.column(col, stretch=tk.YES) else: self.tree.column(col, stretch=tk.NO, width=100) # 调整列宽 self.adjust_columns(None) def remove_confirmation_column(self): """移除确认列""" selection = self.selected_cols_listbox.curselection() if selection: index = selection[0] col = self.confirmation_columns.pop(index) self.selected_cols_listbox.delete(index) # 更新Treeview列 self.update_treeview_columns() def browse_file(self): initial_dir = self.config.get("last_dir", os.getcwd()) file_path = filedialog.askopenfilename( initialdir=initial_dir, filetypes=[("Excel文件", "*.xlsx;*.xls")] ) if file_path: self.path_entry.delete(0, tk.END) self.path_entry.insert(0, file_path) # 更新最后访问目录 self.config["last_dir"] = os.path.dirname(file_path) self.save_config() def select_sheet(self): """选择工作表""" file_path = self.path_entry.get() if not file_path or not os.path.exists(file_path): messagebox.showerror("错误", "请先选择有效的Excel文件") return try: # 获取所有sheet名称 xl = pd.ExcelFile(file_path) sheet_names = xl.sheet_names # 创建现代化选择对话框 sheet_dialog = tk.Toplevel(self.master) sheet_dialog.title("选择工作表") sheet_dialog.geometry("400x300") sheet_dialog.transient(self.master) sheet_dialog.grab_set() sheet_dialog.configure(bg="#f5f7fa") ttk.Label(sheet_dialog, text="请选择工作表:", font=self.subtitle_font, background="#f5f7fa").pack(pady=10) # 使用Treeview显示工作表 sheet_tree = ttk.Treeview(sheet_dialog, columns=("名称",), show="headings", height=8) sheet_tree.heading("名称", text="工作表名称") sheet_tree.column("名称", width=350) sheet_tree.pack(fill="both", expand=True, padx=20, pady=5) for name in sheet_names: sheet_tree.insert("", "end", values=(name,)) # 按钮框架 btn_frame = ttk.Frame(sheet_dialog) btn_frame.pack(fill="x", padx=20, pady=10) def on_select(): selected = sheet_tree.selection() if selected: self.current_sheet = sheet_tree.item(selected[0], "values")[0] self.sheet_var.set(self.current_sheet) sheet_dialog.destroy() # 修复按钮布局问题 ttk.Button(btn_frame, text="取消", command=sheet_dialog.destroy).pack(side="right", padx=5) ttk.Button(btn_frame, text="确定", command=on_select, style="Primary.TButton").pack(side="right") except Exception as e: messagebox.showerror("错误", f"读取Excel失败: {str(e)}") def load_data(self): file_path = self.path_entry.get() if not file_path or not os.path.exists(file_path): messagebox.showerror("错误", "无效的文件路径") return # 获取当前配置 id_col = self.id_col_var.get().strip() desc_col = self.desc_col_var.get().strip() status_col = self.status_col_var.get().strip() sheet_name = self.sheet_var.get() or None header_row = self.header_var.get() - 1 # pandas header是0-based索引 # 在状态栏显示加载中 self.status_var.set("正在加载数据...") self.master.update() def load_task(): try: # 读取Excel文件 if sheet_name: self.df = pd.read_excel( file_path, sheet_name=sheet_name, header=header_row ) else: self.df = pd.read_excel( file_path, header=header_row ) self.excel_path = file_path # 检查列是否存在 missing_cols = [] if id_col not in self.df.columns: missing_cols.append(f"ID列 '{id_col}'") if desc_col not in self.df.columns: missing_cols.append(f"功能点列 '{desc_col}'") if missing_cols: # 提供更详细的错误信息,包括可用列名 available_cols = "\n".join(self.df.columns) error_msg = ( f"以下列不存在: {', '.join(missing_cols)}\n\n" f"可用列名:\n{available_cols}\n\n" "请检查表头行设置是否正确(默认为第9行)" ) raise ValueError(error_msg) # 如果状态列不存在,则创建 if status_col not in self.df.columns: self.df[status_col] = "否" # 默认未确认 # 更新列选择器 self.col_selector["values"] = list(self.df.columns) # 清空Treeview self.tree.delete(*self.tree.get_children()) self.check_vars = {} # 添加数据到Treeview for i, row in self.df.iterrows(): status_value = row.get(status_col, "否") # 使用图标表示状态 status_icon = "✓" if status_value in ["是", "Y", "y", "Yes", "yes", "OK", "确认"] else "✗" status_text = f"{status_icon} {status_value}" tag = "confirmed" if status_icon == "✓" else "pending" # 构建行数据 values = [ "", # 选择列 - 留空,我们将使用自定义复选框 row[id_col], row[desc_col], status_text ] # 添加多列确认数据 for col in self.confirmation_columns: if col in row: values.append(row[col]) else: values.append("") # 插入行 item_id = self.tree.insert("", "end", values=values, tags=(tag,)) # 创建复选框变量 var = tk.BooleanVar(value=(status_icon == "✓")) self.check_vars[item_id] = var # 添加复选框到选择列 self.create_checkbox(item_id, var) # 更新状态 self.status_var.set(f"成功加载: {len(self.df)} 条记录") except Exception as e: self.status_var.set("加载失败") messagebox.showerror("加载错误", f"读取Excel失败: {str(e)}") # 在新线程中加载数据 threading.Thread(target=load_task, daemon=True).start() def create_checkbox(self, item_id, var): """为Treeview中的行创建复选框 (修复方法)""" # 创建Frame作为容器 checkbox_frame = tk.Frame(self.tree) # 创建复选框 cb = ttk.Checkbutton( checkbox_frame, variable=var, style="Custom.TCheckbutton", command=lambda: self.toggle_checkbox(item_id, var) ) cb.pack() # 正确嵌入到Treeview单元格 self.tree.set(item_id, column="选择", value="") # 清空单元格文本 # 获取"选择"列的索引 columns = self.tree["columns"] col_index = columns.index("选择") column_id = f"#{col_index+1}" # 列标识从1开始 # 使用正确的方法嵌入控件 self.tree.window_create(item_id, column=column_id, window=checkbox_frame) # 更新复选框状态 self.update_checkbox_state(item_id, var) def toggle_checkbox(self, item_id, var): """切换复选框状态""" # 更新行的状态显示 self.update_checkbox_state(item_id, var) def update_checkbox_state(self, item_id, var): """根据复选框状态更新行状态""" current_values = list(self.tree.item(item_id, "values")) if var.get(): current_values[3] = "✓ 待确认" self.tree.item(item_id, tags=("confirmed",)) else: current_values[3] = "✗ 未确认" self.tree.item(item_id, tags=("pending",)) self.tree.item(item_id, values=current_values) def confirm_selected(self): """确认选中的功能点""" selected_items = [] for item_id in self.tree.get_children(): if self.check_vars[item_id].get(): selected_items.append(item_id) if not selected_items: messagebox.showinfo("提示", "请先选择功能点") return custom_status = self.custom_status_var.get().strip() or "OK" for item_id in selected_items: self.check_vars[item_id].set(True) current_values = list(self.tree.item(item_id, "values")) # 更新状态列 current_values[3] = f"✓ {custom_status}" # 更新多列确认 if self.confirmation_columns and self.df is not None: row_idx = self.tree.index(item_id) for i, col in enumerate(self.confirmation_columns, start=4): if col in self.df.columns: current_values[i] = custom_status self.df.at[row_idx, col] = custom_status # 更新Treeview self.tree.item(item_id, values=tuple(current_values), tags=("confirmed",)) # 更新复选框状态(触发颜色变化) self.update_checkbox_state(item_id, self.check_vars[item_id]) self.status_var.set(f"已确认 {len(selected_items)} 个功能点") # 自动保存 self.auto_save() def select_all(self): """全选功能点""" for item_id in self.tree.get_children(): var = self.check_vars[item_id] var.set(True) self.update_checkbox_state(item_id, var) self.status_var.set("已全选所有功能点") def deselect_all(self): """取消全选功能点""" for item_id in self.tree.get_children(): var = self.check_vars[item_id] var.set(False) self.update_checkbox_state(item_id, var) self.status_var.set("已取消全选所有功能点") def save_current_config(self): """保存当前配置""" self.config["id_col"] = self.id_col_var.get().strip() self.config["desc_col"] = self.desc_col_var.get().strip() self.config["status_col"] = self.status_col_var.get().strip() self.config["sheet_name"] = self.sheet_var.get() self.config["header_row"] = self.header_var.get() self.config["custom_status"] = self.custom_status_var.get().strip() self.config["confirmation_columns"] = self.confirmation_columns self.save_config() messagebox.showinfo("成功", "配置已保存") def auto_save(self): """自动保存功能""" if self.df is None or not self.excel_path: return try: # 获取当前配置 id_col = self.id_col_var.get().strip() desc_col = self.desc_col_var.get().strip() status_col = self.status_col_var.get().strip() # 更新DataFrame中的确认状态 for i, item_id in enumerate(self.tree.get_children()): # 获取Treeview中的状态值(去掉图标) status_value = self.tree.item(item_id, "values")[3] if status_value.startswith(("✓", "✗")): status_value = status_value[2:].strip() self.df.at[i, status_col] = status_value # 保存回Excel - 使用openpyxl直接操作工作簿 wb = openpyxl.load_workbook(self.excel_path) if self.current_sheet in wb.sheetnames: del wb[self.current_sheet] ws = wb.create_sheet(self.current_sheet) # 写入数据 for r, row in enumerate(dataframe_to_rows(self.df, index=False, header=True), 1): ws.append(row) wb.save(self.excel_path) self.status_var.set("数据已自动保存") except Exception as e: self.status_var.set(f"自动保存失败: {str(e)}") def save_to_excel(self): if self.df is None: messagebox.showerror("错误", "没有加载的数据") return try: # 执行保存 self.auto_save() messagebox.showinfo("成功", f"数据已保存到:\n{self.excel_path}") self.status_var.set("数据保存成功") except Exception as e: messagebox.showerror("保存错误", f"写入Excel失败: {str(e)}\n请确保文件未被其他程序打开") def main(): root = tk.Tk() # 设置应用图标 try: # 创建一个简单的蓝色方块作为图标 icon_data = """ R0lGODlhEAAQAIAAAP///wAAACH5BAEAAAAALAAAAAAQABAAAAIOhI+py+0Po5y02ouzPgUAOw== """ icon_img = tk.PhotoImage(data=icon_data) root.tk.call('wm', 'iconphoto', root._w, icon_img) except: pass app = ExcelControlPanel(root) root.mainloop() if __name__ == "__main__": main() 还是会报加载错误 读取Excel失败: ‘Treeview’ object has no attribute ‘window_create’,请更换一种方式进行编辑
最新发布
08-01
<think>我们尝试使用另一种方法在Treeview中嵌入复选框:使用`ttk.Treeview`的`tag_bind`和`item`配置,通过绘制一个复选框图像来模拟,或者使用`place`方法将复选框放置在Treeview单元格上。但是,这些方法都有其复杂性。 考虑到我们之前的方法在嵌入控件时遇到了问题,我们可以尝试使用`place`方法将复选框放置在Treeview的单元格上。具体步骤如下: 1. 在Treeview中,我们为每一行的第一列(“选择”列)留空。 2. 在Treeview中插入行后,我们根据该行的位置和单元格的坐标,将复选框放置在对应的单元格上。 3. 当Treeview滚动时,我们需要重新放置复选框(或者使用一个Canvas来包含Treeview和复选框,但这样更复杂)。 然而,这种方法在滚动和调整大小时需要重新计算位置,比较繁琐且容易出错。 另一种更可靠的方法是使用`ttk.Treeview`的`item`方法,将第一列的值设置为一个字符串(如"☐"表示未选中,"☑"表示选中),然后通过绑定事件(如单击事件)来切换这个状态。这种方法不需要嵌入实际的Checkbutton控件,而是用文本模拟复选框。 我们将采用文本模拟的方法: 步骤: 1. 在创建Treeview行时,第一列的值设置为"☐"(未选中)或"☑"(选中)。 2. 为Treeview绑定事件(如`<Button-1>`),当点击第一列时,切换该状态。 3. 切换状态时,同时更新该行对应的复选框变量(self.check_vars)和行的显示。 这样,我们避免了嵌入控件,从而解决了`window_create`方法不可用的问题。 修改如下: 1. 在`load_data`方法中,为每一行创建时,根据状态设置第一列为"☑"(已确认)或"☐"(未确认)。 2. 创建一个事件处理函数`on_treeview_click`,用于处理Treeview的点击事件。当点击的是第一列时,切换该单元格的文本,并更新状态。 3. 移除原来的`create_checkbox`方法和相关的复选框创建代码。 注意:我们不再需要`self.check_vars`作为BooleanVar的字典,而是可以直接使用一个字典来存储每个item_id的选中状态(或者直接从单元格文本读取状态)。 但是,为了保持代码其他部分(如全选、取消全选)的功能,我们可以保留`self.check_vars`,但改为存储每个item_id的选中状态(布尔值),并在点击时更新。 具体实现: 1. 修改`load_data`方法中创建行时的代码: - 对于每个行,根据初始状态设置第一列的值为"☑"(如果已确认)或"☐"(如果未确认)。 - 同时,在`self.check_vars[item_id]`中存储一个布尔值表示选中状态。 2. 绑定Treeview的点击事件: ```python self.tree.bind("<Button-1>", self.on_treeview_click) ``` 3. 实现`on_treeview_click`方法: - 判断点击的区域(使用`identify_region`和`identify_column`)是否为第一列(即“选择”列)。 - 如果是,获取点击的行(`identify_row`),切换该行的第一列文本和选中状态。 - 更新`self.check_vars`中的状态。 4. 修改`update_checkbox_state`方法(如果需要)或直接在该事件中更新状态。 5. 修改`select_all`和`deselect_all`方法,直接设置第一列的文本和`self.check_vars`中的值。 6. 在`confirm_selected`方法中,我们根据`self.check_vars`中的值来确定哪些行被选中。 这种方法避免了嵌入控件,因此不会出现`window_create`的问题。 下面,我们将按照这个思路修改代码。</think>我理解您遇到了 Treeview 的 `window_create` 方法问题。让我们采用一种更可靠的方法来实现在 Treeview 中嵌入复选框的功能。我将使用以下替代方案: ### 解决方案:使用文本模拟复选框 + 事件绑定 我们将使用 Unicode 字符来模拟复选框,并通过事件绑定来处理用户交互: ```python import pandas as pd import tkinter as tk from tkinter import ttk, messagebox, filedialog import os import json import threading import openpyxl from openpyxl.utils.dataframe import dataframe_to_rows from tkinter.font import Font class ScrollableFrame(ttk.Frame): """自定义可滚动框架实现""" def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) # 创建Canvas和滚动条 self.canvas = tk.Canvas(self) self.scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview) self.scrollable极ame = ttk.Frame(self.canvas) # 配置Canvas self.canvas.configure(yscrollcommand=self.scrollbar.set) self.canvas_frame = self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw") # 布局 self.canvas.pack(side="left", fill="both", expand=True) self.scrollbar.pack(side="right", fill="y") # 绑定事件 self.scrollable_frame.bind("<Configure>", self.on_frame_configure) self.canvas.bind("<Configure>", self.on_canvas_configure) self.canvas.bind_all("<MouseWheel>", self.on_mousewheel) def on_frame_configure(self, event): """当内部框架大小改变时更新滚动区域""" self.canvas.configure(scrollregion=self.canvas.bbox("all")) def on_canvas_configure(self, event): """当Canvas大小改变时调整内部框架宽度""" self.canvas.itemconfig(self.canvas_frame, width=event.width) def on_mousewheel(self, event): """鼠标滚轮滚动支持""" self.canvas.yview_scroll(int(-1*(event.delta/120)), "units") class ExcelControlPanel: def __init__(self, master): self.master = master master.title("功能点确认系统") master.geometry("1280x800") master.configure(bg="#f0f2f5") # 设置全局样式 self.set_styles() # 加载配置 self.config = self.load_config() # 初始化多列确认配置 self.confirmation_columns = self.config.get("confirmation_columns", []) # 创建界面元素 self.create_widgets() # 初始化数据 self.excel_path = "" self.df = None self.check_states = {} # 存储每个功能点的复选框状态,key为item_id self.current_sheet = "" self.header_row = 0 # 启用列拖动 self.enable_column_dragging() def set_styles(self): """设置全局样式和字体""" style = ttk.Style() style.theme_use('clam') # 自定义字体 self.title_font = Font(family="Microsoft YaHei", size=16, weight="bold") self.subtitle_font = Font(family="Microsoft YaHei", size=12) self.normal_font = Font(family="Microsoft YaHei", size=10) # 配置样式 style.configure("TFrame", background="#f0f2f5") style.configure("TLabel", font=self.normal_font, background="#f0f2f5", foreground="#333") style.configure("TButton", font=self.normal_font, padding=8) style.configure("Treeview.Heading", font=self.subtitle_font, background="#4a76b5", foreground="white") style.configure("Treeview", font=self.normal_font, rowheight=30, background="white", fieldbackground="white") style.configure("Title.TLabel", font=self.title_font, background="#4a76b5", foreground="white", padding=10) style.configure("Status.TLabel", font=self.normal_font, background="#333", foreground="#fff", padding=5) style.configure("Card.TFrame", background="white", borderwidth=0, relief="solid", padding=10, bordercolor="#e1e4e8", borderradius=8) style.configure("Card.TLabelframe", background极white", borderwidth=1, relief="solid", padding=10, bordercolor="#e1e4e8", borderradius=8) style.configure("Card.TLabelframe.Label", font=self.subtitle_font, foreground="#2c3e50", background="white") # 按钮样式 style.map("Primary.TButton", background=[("active", "#3a66a5"), ("pressed", "#2a5685")], foreground=[("active", "white"), ("pressed", "white")]) style.configure("Primary.TButton", background="#4a76b5", foreground="white", font=self.subtitle_font, borderwidth=0, borderradius=4) style.map("Success.TButton", background=[("active", "#28a745"), ("pressed", "#218838")], foreground=[("active", "white"), ("pressed", "white")]) style.configure("Success.TButton", background="#28a745", foreground="white", font=self.subtitle_font, borderwidth=0, borderradius=4) style.map("Danger.TButton", background=[("active", "#dc3545"), ("pressed", "#c82333")], foreground=[("active", "white"), ("pressed", "white")]) style.configure("Danger.TButton", background="#dc3545", foreground="white", font=self.subtitle_font, borderwidth=0, borderradius=4) # 输入框样式 style.configure("Custom.TEntry", fieldbackground="#f8f9fa", bordercolor="#ced4da") def load_config(self): """加载配置文件""" config_path = "excel_config.json" default_config = { "id_col": "No.", "desc_col": "レビュー観点(CHN)", "status_col": "レビュー結果", "sheet_name": "", "header_row": 9, "last_dir": os.getcwd(), "custom_status": "OK", "confirmation_columns": [] } if os.path.exists(config_path): try: with open(config_path, 'r', encoding='utf-8') as f: config = json.load(f) # 确保所有键都存在 for key in default_config: if key not in config: config[key] = default_config[key] return config except: return default_config return default_config def save_config(self): """保存配置文件""" config_path = "excel_config.json" with open(config_path, 'w', encoding='utf-8') as f: json.dump(self.config, f, ensure_ascii=False, indent=2) def create_widgets(self): """创建现代化界面元素""" # 主容器 main_container = ttk.Frame(self.master, style="Card.TFrame") main_container.pack(fill="both", expand=True, padx=20, pady=20) # 标题栏 title_frame = ttk.Frame(main_container, style="Title.TFrame") title_frame.pack(fill="x", pady=(0, 20)) # 添加内置图标 try: # 创建一个简单的内置图标 self.icon_img = tk.PhotoImage(width=32, height=32) self.icon_img.put("#4a76b5", (0, 0, 32, 32)) icon_label = ttk.Label(title_frame, image=self.icon_img, background="#4a76b5") icon_label.pack(side="left", padx=(15, 10)) except: pass ttk.Label(title_frame, text="功能点确认系统", style="Title.TLabel").pack(side="left", padx=10) # 主内容区域(卡片式布局) content_frame = ttk.Frame(main_container) content_frame.pack(fill="both", expand=True) # 左侧控制面板(卡片) - 可滚动 control_container = ttk.Frame(content_frame, width=350) control_container.pack(side="left", fill="y", padx=(0, 20)) # 创建自定义可滚动框架 scrollable_frame = ScrollableFrame(control_container, width=350) scrollable_frame.pack(fill="both", expand=True) # 获取内部框架 inner_frame = scrollable_frame.scrollable_frame # 美化控制面板 control_card = ttk.LabelFrame(inner_frame, text="控制面板", style="Card.TLabelframe") control_card.pack(fill="both", expand=True, padx=10, pady=10, ipadx=5, ipady=5) # 文件选择区域 file_frame = ttk.LabelFrame(control_card, text="Excel文件设置") file_frame.pack(fill="x", padx=10, pady=(0, 15)) ttk.Label(file_frame, text="Excel文件路径:").pack(anchor="w", pady=(0, 5), padx=10) path_frame = ttk.Frame(file_frame) path_frame.pack(fill="x", pady=5, padx=10) self.path_entry = ttk.Entry(path_frame, width=30, style="Custom.TEntry") self.path_entry.pack(side="left", fill="x", expand=True, padx=(极, 5)) ttk.Button(path_frame, text="浏览", command=self.browse_file, width=8).pack(side="left") ttk.Button(file_frame, text="加载数据", command=self.load_data, style="Primary.TButton").pack(fill="x", pady=10, padx=10) # Sheet选择区域 sheet_frame = ttk.LabelFrame(control_card, text="工作表设置") sheet_frame.pack(fill="x", padx=10, pady=(0, 15)) ttk.Label(sheet_frame, text="当前Sheet:").pack(anchor="w", padx=10, pady=(10, 0)) self.sheet_var = tk.StringVar(value=self.config.get("sheet_name", "未选择")) sheet_display = ttk.Label(sheet_frame, textvariable=self.sheet_var, font=self.subtitle_font) sheet_display.pack(anchor="w", pady=(0, 10), padx=10) ttk.Button(sheet_frame, text="选择工作表", command=self.select_sheet, style="Primary.TButton").pack(fill="x", padx=10, pady=(0, 10)) # 表头行设置 header_frame = ttk.LabelFrame(control_card, text="表头设置") header_frame.pack(fill="x", padx=10, pady=(0, 15)) ttk.Label(header_frame, text="表头所在行号:").pack(anchor="w", padx=10, pady=(10, 0)) self.header_var = tk.IntVar(value=self.config.get("header_row", 9)) ttk.Entry(header_frame, textvariable=self.header_var, width=10, style="Custom.TEntry").pack(anchor="w", pady=5, padx=10) # 列名配置区域 col_frame = ttk.LabelFrame(control_card, text="列名配置") col_frame.pack(fill="x", padx=10, pady=(0, 15)) # ID列 ttk.Label(col_frame, text="ID列名:").pack(anchor="w", padx=10, pady=(10, 0)) self.id_col_var = tk.StringVar(value=self.config["id_col"]) ttk.Entry(col_frame, textvariable=self.id_col_var, style="Custom.TEntry").pack(fill="x", pady=(0, 10), padx=10) # 功能点列 ttk.Label(col_frame, text="功能点列名:").pack(anchor="w", padx=10, pady=(0, 0)) self.desc_col_var = tk.StringVar(value=self.config["desc_col"]) ttk.Entry(col_frame, textvariable=self.desc_col_var, style="Custom.TEntry").pack(fill="x", pady=(0, 10), padx=10) # 状态列 ttk.Label(col_frame, text="状态列名:").pack(anchor="w", padx=10, pady=(0, 0)) self.status_col_var = tk.StringVar(value=self.config["status_col"]) ttk.Entry(col_frame, textvariable=self.status_col_var, style="Custom.TEntry").pack(fill="x", pady=(0, 10), padx=10) # 自定义状态 ttk.Label(col_frame, text="自定义确认状态:").pack(anchor="w", padx=10, pady=(0, 0)) self.custom_status_var = tk.StringVar(value=self.config.get("custom_status", "OK")) ttk.Entry(col_frame, textvariable=self.custom_status_var, style="Custom.TEntry").pack(fill="x", pady=(0, 10), padx=10) # 多列确认设置 multi_col_frame = ttk.LabelFrame(control_card, text="多列确认设置") multi_col_frame.pack(fill="x", padx=10, pady=(0, 15)) # 列选择器 ttk.Label(multi_col_frame, text="选择要确认的列:").pack(anchor="w", padx=10, pady=(10, 0)) col_selector_frame = ttk.Frame(multi_col_frame) col_selector_frame.pack(fill="x", pady=5, padx=10) self.col_selector = ttk.Combobox(col_selector_frame, state="readonly", width=15, style="Custom.TCombobox") self.col_selector.pack(side="left", fill="x", expand=True, padx=(0, 5)) # 添加/移除按钮 ttk.Button(col_selector_frame, text="添加", command=self.add_confirmation_column, width=8).pack(side="left") # 已选列列表 ttk.Label(multi_col_frame, text="已选确认列 (可拖动调整顺序):").pack(anchor="w", padx=10, pady=(10, 0)) self.selected_cols_listbox = tk.Listbox(multi_col_frame, height=3, font=self.normal_font, bg="#f8f9fa", highlightthickness=0) self.selected_cols_listbox.pack(fill="x", pady=5, padx=10) # 加载已配置的确认列 for col in self.confirmation_columns: self.selected_cols_listbox.insert(tk.END, col) # 移除按钮 remove_btn = ttk.Button(multi_col_frame, text="移除选中极", command=self.remove_confirmation_column) remove_btn.pack(fill="x", pady=(0, 10), padx=10) # 操作按钮区域 btn_frame = ttk.Frame(control_card) btn_frame.pack(fill="x", padx=10, p极=10) ttk.Button(btn_frame, text="保存配置", command=self.save_current_config, style="Success.TButton").pack(fill="x", pady=5) ttk.Button(btn_frame, text="确认选中项", command=self.confirm_selected, style="Primary.TButton").pack(fill="x", pady=5) ttk.Button(btn_frame, text="全选", command=self.select_all, style="Primary.TButton").pack(side="left", fill="x", expand=True, padx=(0, 5), pady=5) ttk.Button(btn_frame, text="取消全选", command=self.deselect_all, style="Danger.TButton").pack(side="left", fill="x", expand=True, padx=(5, 0), pady=5) ttk.Button(btn_frame, text="保存到Excel", command=self.save_to_excel, style="Success.TButton").pack(fill="x", pady=5) # 数据显示区域(卡片) data_card = ttk.LabelFrame(content_frame, text="功能点列表", style="Card.TLabelframe") data_card.pack(side="right", fill="both", expand=True) # 创建带滚动条的表格 columns = ("选择", "ID", "功能点", "状态") self.tree = ttk.Treeview(data_card, columns=columns, show="headings", height=20) vsb = ttk.Scrollbar(data_card, orient="vertical", command=self.tree.yview) hsb = ttk.Scrollbar(data_card, orient="horizontal", command=self.tree.xview) self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set) # 添加分割条和详情文本框 paned_window = tk.PanedWindow(data_card, orient=tk.VERTICAL, sashrelief=tk.RAISED, sashwidth=4) paned_window.pack(fill="both", expand=True, padx=5, pady=5) # 将Treeview放入PanedWindow的上部分 tree_frame = ttk.Frame(paned_window) paned_window.add(tree_frame) self.tree.pack(in_=tree_frame, side="top", fill="both", expand=True) vsb.pack(in_=tree_frame, side="right", fill="y", padx=(0, 5), pady=5) hsb.pack(in_=tree_frame, side="bottom", fill="x", padx=5, pady=(0, 5)) # 配置列 col_widths = {"选择": 50, "ID": 120, "功能点": 600, "状态": 120} for col in columns: self.tree.heading(col, text=col, anchor="w") self.tree.column(col, width=col_widths[col], minwidth=50, stretch=tk.YES if col == "功能点" else tk.NO) # 添加标签样式 self.tree.tag_configure("confirmed", background="#d4edda") self.tree.tag_configure("pending", background="#f8d7da") # 绑定列调整事件 self.tree.bind("<Configure>", self.adjust_columns) # 绑定点击事件处理复选框 self.tree.bind("<Button-1>", self.on_tree_click) # 添加详情文本框 detail_frame = ttk.Frame(paned_window, height=100) paned_window.add(detail_frame) ttk.Label(detail_frame, text="功能点详情:").pack(anchor="w", padx=5, pady=5) self.detail_text = tk.Text(detail_frame, wrap="word", font=self.normal_font, height=5) scroll_detail = ttk.Scrollbar(detail_frame, command=self.detail_text.yview) self.detail_text.config(yscrollcommand=scroll_detail.set) self.detail_text.pack(side="left", fill="both", expand=True, padx=5, pady=5) scroll_detail.pack(side="right", fill="y", padx=(0, 5), pady=5) self.detail_text.config(state="disabled") # 绑定Treeview选择事件 self.tree.bind("<<TreeviewSelect>>", self.on_tree_select) # 状态栏 self.status_var = tk.StringVar() self.status_var.set("就绪 - 请选择Excel文件开始") status_bar = ttk.Label(self.master, textvariable=self.status_var, style="Status.TLabel") status_bar.pack(side="bottom", fill="x") def on_tree_select(self, event): """当Treeview中选中行时,显示功能点详情""" selected_items = self.tree.selection() if not selected_items: return item = selected_items[0] # 获取功能点描述,在第三列(索引2) values = self.tree.item(item, "values") if len(values) >= 3: desc = values[2] self.detail_text.config(state="normal") self.detail_text.delete(1.0, tk.END) self.detail_text.insert(tk.END, desc) self.detail_text.config(state="disabled") def on_tree_click(self, event): """处理Treeview点击事件,切换复选框状态""" region = self.tree.identify("region", event.x, event.y) if region == "cell": column = self.tree.identify_column(event.x) item = self.tree.identify_row(event.y) # 只处理"选择"列(第一列) if column == "#1" and item: # 获取当前状态 values = list(self.tree.item(item, "values")) current_state = values[0] # 切换状态 if current_state == "☐": new_state = "☑" else: new_state = "☐" # 更新Treeview values[0] = new_state self.tree.item(item, values=values) # 更新状态存储 self.check_states[item] = (new_state == "☑") # 更新行的整体状态显示 self.update_row_status(item) def update_row_status(self, item_id): """根据复选框状态更新行状态显示""" values = list(self.tree.item(item_id, "values")) is_checked = self.check_states.get(item_id, False) if is_checked: values[3] = "✓ 待确认" self.tree.item(item_id, tags=("confirmed",)) else: values[3] = "✗ 未确认" self.tree.item(item_id, tags=("pending",)) self.tree.item(item_id, values=values) def enable_column_dragging(self): """启用列拖动功能""" def on_header_click(event): # 记录开始拖动的列 region = self.tree.identify("region", event.x, event.y) if region == "heading": self.drag_start_col = self.tree.identify_column(event.x) def on_header_drag(event): # 处理拖动中的列 if hasattr(self, 'drag_start_col'): region = self.tree.identify("region", event.x, event.y) if region == "heading": end_col = self.tree.identify_column(event.x) if end_col != self.drag_start_col: # 移动列 self.move_column(self.drag_start_col, end_col) self.drag_start_col = end_col def on_header_release(event): # 结束拖动 if hasattr(self, 'drag_start_col'): del self.drag_start_col # 绑定事件 self.tree.bind("<ButtonPress-1>", on_header_click) self.tree.bind("<B1-Motion>", on_header_drag) self.tree.bind("<ButtonRelease-1>", on_header_release) def move_column(self, from_col, to_col): """移动列位置""" # 获取当前列顺序 columns = list(self.tree["columns"]) # 转换为索引 from_idx = int(from_col.replace("#", "")) - 1 to_idx = int(to_col.replace("#", "")) - 1 # 移动列 if from_idx < len(columns) and to_idx < len(columns): col = columns.pop(from_idx) columns.insert(to_idx, col) # 更新列顺序 self.tree["columns"] = columns # 重新配置列 for i, col in enumerate(columns): self.tree.heading(col, text=col) self.tree.column(col, anchor="w") # 调整列宽 self.adjust_columns(None) def adjust_columns(self, event): """根据窗口大小自动调整列宽""" if not self.tree.winfo_exists(): return width = self.tree.winfo_width() if width < 100: # 防止宽度过小 return # 设置列宽比例:选择 5%,ID 15%,功能点 70%,状态 10% self.tree.column("选择", width=int(width * 0.05)) self.tree.column("ID", width=int(width * 0.15)) self.tree.column("功能点", width=int(width * 0.7)) self.tree.column("状态", width=int(width * 0.1)) # 调整多列确认的列宽 if self.confirmation_columns: for col in self.confirmation_columns: self.tree.column(col, width=int(width * 0.1)) def add_confirmation_column(self): """添加确认列""" col = self.col_selector.get() if col and col not in self.confirmation_columns: self.confirmation_columns.append(col) self.selected_cols_listbox.insert(tk.END, col) # 更新Treeview列 self.update_treeview_columns() def update_treeview_columns(self): """更新Treeview列以显示确认列""" # 构建列列表 columns = ["选择", "ID", "功能点", "状态"] + self.confirmation_columns # 重新配置Treeview self.tree.configure(columns=columns) self.tree["show"] = "headings" # 设置列标题 for col in columns: self.tree.heading(col, text=col) # 设置最小宽度和拉伸属性 if col == "功能点": self.tree.column(col, stretch=tk.YES) else: self.tree.column(col, stretch=tk.NO, width=100) # 调整列宽 self.adjust_columns(None) def remove_confirmation_column(self): """移除确认列""" selection = self.selected_cols_listbox.curselection() if selection: index = selection[0] col = self.confirmation_columns.pop(index) self.selected_cols_listbox.delete(index) # 更新Treeview列 self.update_treeview_columns() def browse_file(self): initial_dir = self.config.get("last_dir", os.getcwd()) file_path = filedialog.askopenfilename( initialdir=initial_dir, filetypes=[("Excel文件", "*.xlsx;*.xls")] ) if file_path: self.path_entry.delete(0, tk.END) self.path_entry.insert(0, file_path) # 更新最后访问目录 self.config["last_dir"] = os.path.dirname(file_path) self.save_config() def select_sheet(self): """选择工作表""" file_path = self.path_entry.get() if not file_path or not os.path.exists(file_path): messagebox.showerror("错误", "请先选择有效的Excel文件") return try: # 获取所有sheet名称 xl = pd.ExcelFile(file_path) sheet_names = xl.sheet_names # 创建现代化选择对话框 sheet_dialog = tk.Toplevel(self.master) sheet_dialog.title("选择工作表") sheet_dialog.geometry("400x300") sheet_dialog.transient(self.master) sheet_dialog.grab_set() sheet_dialog.configure(bg="#f5f7fa") ttk.Label(sheet_dialog, text="请选择工作表:", font=self.subtitle_font, background="#极f7fa").pack(pady=10) # 使用Treeview显示工作表 sheet_tree = ttk.Treeview(sheet_dialog, columns=("名称",), show="headings", height=8) sheet_tree.heading("名称", text="工作表名称") sheet_tree.column("名称", width=350) sheet_tree.pack(fill="both", expand=True, padx=20, pady=5) for name in sheet_names: sheet_tree.insert("", "end", values=(name,)) # 按钮框架 btn_frame = ttk.Frame(sheet_dialog) btn_frame.pack(fill="x", padx=20, pady=10) def on_select(): selected = sheet_tree.selection() if selected: self.current_sheet = sheet_tree.item(selected[0], "values")[0] self.sheet_var.set(self.current_sheet) sheet_dialog.destroy() # 修复按钮布局问题 ttk.Button(btn_frame, text="取消", command=sheet_dialog.destroy).pack(side="right", padx=5) ttk.Button(btn_frame, text="确定", command=on_select, style="Primary.TButton").pack(side="right") except Exception as e: messagebox.showerror("错误", f"读取Excel失败: {str(e)}") def load_data(self): file_path = self.path_entry.get() if not file_path or not os.path.exists(file_path): messagebox.showerror("错误", "无效的文件路径") return # 获取当前配置 id_col = self.id_col_var.get().strip() desc_col = self.desc_col_var.get().strip() status_col = self.status_col_var.get().strip() sheet_name = self.sheet_var.get() or None header_row = self.header_var.get() - 1 # pandas header是0-based索引 # 在状态栏显示加载中 self.status_var.set("正在加载数据...") self.master.update() def load_task(): try: # 读取Excel文件 if sheet_name: self.df = pd.read_excel( file_path, sheet_name=sheet_name, header=header_row ) else: self.df = pd.read_excel( file_path, header=header_row ) self.excel_path = file_path # 检查列是否存在 missing_cols = [] if id_col not in self.df.columns: missing_cols.append(f"ID列 '{id_col}'") if desc_col not in self.df.columns: missing_cols.append(f"功能点列 '{desc_col}'") if missing_cols: # 提供更详细的错误信息,包括可用列名 available_cols = "\n".join(self.df.columns) error_msg = ( f"以下列不存在: {', '.join(missing_cols)}\n\n" f"可用列名:\n{available_cols}\n\n" "请检查表头行设置是否正确(默认为第9行)" ) raise ValueError(error_msg) # 如果状态列不存在,则创建 if status_col not in self.df.columns: self.df[status_col] = "否" # 默认未确认 # 更新列选择器 self.col_selector["values"] = list(self.df.columns) # 清空Treeview self.tree.delete(*self.tree.get_children()) self.check_states = {} # 添加数据到Treeview for i, row in self.df.iterrows(): status_value = row.get(status_col, "否") # 使用图标表示状态 status_icon = "✓" if status_value in ["是", "Y", "y", "Yes", "yes", "OK", "确认"] else "✗" status_text = f"{status_icon} {status_value}" tag = "confirmed" if status_icon == "✓" else "pending" # 构建行数据 values = [ "☐", # 选择列 - 初始为未选中 row[id_col], row[desc_col], status_text ] # 添加多列确认数据 for col in self.confirmation_columns: if col in row: values.append(row[col]) else: values.append("") # 插入行 item_id = self.tree.insert("", "end", values=values, tags=(tag,)) # 存储复选框状态 self.check_states[item_id] = False # 更新状态 self.status_var.set(f"成功加载: {len(self.df)} 条记录") except Exception as e: self.status_var.set("加载失败") messagebox.showerror("加载错误", f"读取Excel失败: {str(e)}") # 在新线程中加载数据 threading.Thread(target=load_task, daemon=True).start() def confirm_selected(self): """确认选中的功能点""" selected_items = [] for item_id in self.tree.get_children(): if self.check_states.get(item_id, False): selected_items.append(item_id) if not selected_items: messagebox.showinfo("提示", "请先选择功能点") return custom_status = self.custom_status_var.get().strip() or "OK" for item_id in selected_items: values = list(self.tree.item(item_id, "values")) # 更新状态列 values[3] = f"✓ {custom_status}" # 更新多列确认 if self.confirmation_columns and self.df is not None: row_idx = self.tree.index(item_id) for i, col in enumerate(self.confirmation_columns, start=4): if col in self.df.columns: values[i] = custom_status self.df.at[row_idx, col] = custom_status # 更新Treeview self.tree.item(item_id, values=tuple(values), tags=("confirmed",)) self.status_var.set(f"已确认 {len(selected_items)} 个功能点") # 自动保存 self.auto_save() def select_all(self): """全选功能点""" for item_id in self.tree.get_children(): values = list(self.tree.item(item_id, "values")) values[0] = "☑" # 设置为选中状态 self.tree.item(item_id, values=values) self.check_states[item_id] = True self.update_row_status(item_id) self.status_var.set("已全选所有功能点") def deselect_all(self): """取消全选功能点""" for item_id in self.tree.get_children(): values = list(self.tree.item(item_id, "values")) values[0] = "☐" # 设置为未选中状态 self.tree.item(item_id, values=values) self.check_states[item_id] = False self.update_row_status(item_id) self.status_var.set("已取消全选所有功能点") def save_current_config(self): """保存当前配置""" self.config["id_col"] = self.id_col_var.get().strip() self.config["desc_col"] = self.desc_col_var.get().strip() self.config["status_col"] = self.status_col_var.get().strip() self.config["sheet_name"] = self.sheet_var.get() self.config["header_row"] = self.header_var.get() self.config["custom_status"] = self.custom_status_var.get().strip() self.config["confirmation_columns"] = self.confirmation_columns self.save_config() messagebox.showinfo("成功", "配置已保存") def auto_save(self): """自动保存功能""" if self.df is None or not self.excel_path: return try: # 获取当前配置 id_col = self.id_col_var.get().strip() desc_col = self.desc_col_var.get().strip() status_col = self.status_col_var.get().strip() # 更新DataFrame中的确认状态 for i, item_id in enumerate(self.tree.get_children()): # 获取Treeview中的状态值(去掉图标) status_value = self.tree.item(item_id, "values")[3] if status_value.startswith(("✓", "✗")): status_value = status_value[2:].strip() self.df.at[i, status_col] = status_value # 保存回Excel - 使用openpyxl直接操作工作簿 wb = openpyxl.load_workbook(self.excel_path) if self.current_sheet in wb.sheetnames: del wb[self.current_sheet] ws = wb.create_sheet(self.current_sheet) # 写入数据 for r, row in enumerate(dataframe_to_rows(self.df, index=False, header=True), 1): ws.append(row) wb.save(self.excel_path) self.status_var.set("数据已自动保存") except Exception as e: self.status_var.set(f"自动保存失败: {str(e)}") def save_to_excel(self): if self.df is None: messagebox.showerror("错误", "没有加载的数据") return try: # 执行保存 self.auto_save() messagebox.showinfo("成功", f"数据已保存到:\n{self.excel_path}") self.status_var.set("数据保存成功") except Exception as e: messagebox.showerror("保存错误", f"写入Excel失败: {str(e)}\n请确保文件未被其他程序打开") def main(): root = tk.Tk() # 设置应用图标 try: # 创建一个简单的蓝色方块作为图标 icon_data = """ R0lGODlhEAAQAIAAAP///wAAACH5BAEAAAAALAAAAAAQABAAAAIOhI+py+0Po5y02ouzPgUAOw== """ icon_img = tk.PhotoImage(data=icon_data) root.tk.call('wm', 'iconphoto', root._w, icon_img) except: pass app = ExcelControlPanel(root) root.mainloop() if __name__ == "__main__": main() ``` ### 关键更改说明: 1. **使用文本符号代替真实复选框**: ```python # 在 load_data 方法中 values = [ "☐", # 选择列 - 初始为未选中 row[id_col], row[desc_col], status_text ] ``` 2. **添加点击事件处理**: ```python # 在 create_widgets 方法中 self.tree.bind("<Button-1>", self.on_tree_click) # 实现点击处理 def on_tree_click(self, event): region = self.tree.identify("region", event.x, event.y) if region == "cell": column = self.tree.identify_column(event.x) item = self.tree.identify_row(event.y) # 只处理"选择"列(第一列) if column == "#1" and item: # 切换状态 values = list(self.tree.item(item, "values")) if values[0] == "☐": new_state = "☑" else: new_state = "☐" # 更新Treeview values[0] = new_state self.tree.item(item, values=values) # 更新状态存储 self.check_states[item] = (new_state == "☑") # 更新行的整体状态显示 self.update_row_status(item) ``` 3. **简化状态管理**: ```python # 使用字典存储状态 self.check_states = {} # 存储每个功能点的复选框状态,key为item_id # 全选/取消全选实现 def select_all(self): for item_id in self.tree.get_children(): values = list(self.tree.item(item_id, "values")) values[0] = "☑" # 设置为选中状态 self.tree.item(item_id, values=values) self.check_states[item_id] = True self.update_row_status(item_id) ``` 4. **更新行状态**: ```python def update_row_status(self, item_id): values = list(self.tree.item(item_id, "values")) is_checked = self.check_states.get(item_id, False) if is_checked: values[3] = "✓ 待确认" self.tree.item(item_id, tags=("confirmed",)) else: values[3] = "✗ 未确认" self.tree.item(item_id, tags=("pending",)) self.tree.item(item_id, values=values) ``` ### 这种方法的好处: 1. **跨平台兼容**:不需要依赖特定控件方法 2. **性能更好**:特别适合大量数据 3. **维护简单**:状态管理更直接 4. **视觉效果相似**:使用 ☐ 和 ☑ 符号模拟复选框 ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值