如何用Python和Tkinter实现Treeview双击填充指定Entry字段?
问题:Treeview双击行填充对应Entry控件
我正在学习Python,需要实现以下功能:当数据加载到Treeview后,双击其中的行,将该行的NroCotizacion和NumeroPoliza字段内容填充到对应的Entry控件(EntryNumeroPoliza、EntryNroCotizacion)中以便修改,但不知道如何为代码添加双击事件函数。相关代码如下:
import tkinter as tk from tkinter import ttk from tkcalendar import DateEntry from tree_data import cargaDatos, obtener_fechas def crearVentana(): global tree # Utilizar la variable global tree ventana = tk.Tk() # Cambio aquí, crea una nueva ventana principal ventana.title("Ventana PreFactura") ventana.geometry("1200x700") # Establecer el tamaño de la ventana # Obtener las dimensiones de la pantalla screen_width = ventana.winfo_screenwidth() screen_height = ventana.winfo_screenheight() # Calcular la posición de la ventana para que esté centrada window_width = 1200 window_height = 600 x = (screen_width - window_width) // 2 y = (screen_height - window_height) // 2 ventana.geometry(f"{window_width}x{window_height}+{x}+{y}") frame_calendarios = tk.Frame(ventana) frame_calendarios.pack(pady=10) # Título centrado titulo_label = tk.Label(frame_calendarios, text="Este es un título centrado", font=("Helvetica", 16)) titulo_label.grid(row=0, column=1, columnspan=5, pady=10) label_inicio = tk.Label(frame_calendarios, text="Fecha Inicio") label_inicio.grid(row=1, column=1, padx=10, pady=5) cal_inicio = DateEntry(frame_calendarios, date_pattern='dd/mm/yyyy') cal_inicio.grid(row=1, column=2, padx=(0,150), pady=5) label_fin = tk.Label(frame_calendarios, text="Fecha Termino") label_fin.grid(row=1, column=4, padx=(50,0), pady=5) cal_fin = DateEntry(frame_calendarios, date_pattern='dd/mm/yyyy') cal_fin.grid(row=1, column=5, padx=(0,100), pady=5) btn_aceptar = tk.Button(frame_calendarios, text="Buscar Prefactura", command=lambda: obtener_fechas(cal_inicio, cal_fin, tree)) btn_aceptar.grid(row=2, column=1, columnspan=5, pady=10) tree = ttk.Treeview(ventana, columns=("FechaEmision", "FechaTarificacion", "FechaSolicitud", "InicioVigencia", "NroCotizacion","NumeroPoliza", "NumeroCertificado"), show="headings") tree.heading("FechaEmision", text="FechaEmision") tree.heading("FechaTarificacion", text="FechaTarificacion") tree.heading("FechaSolicitud", text="FechaSolicitud") tree.heading("InicioVigencia", text="InicioVigencia") tree.heading("NroCotizacion", text="NroCotizacion") tree.heading("NumeroPoliza", text="NumeroPoliza") tree.heading("NumeroCertificado", text="NumeroCertificado") tree.pack(fill="both", expand=True) lblNumeroPoliza = tk.Label(frame_calendarios, text="Numero Poliza") lblNumeroPoliza.grid(row=3, column=0, padx=10, pady=5) EntryNumeroPoliza = tk.Entry(frame_calendarios) EntryNumeroPoliza.grid(row=3, column=1, padx=10, pady=5) lblNroCotizacion = tk.Label(frame_calendarios, text="Numero Cotizacion") lblNroCotizacion.grid(row=3, column=2, padx=0, pady=0) EntryNroCotizacion = tk.Entry(frame_calendarios) EntryNroCotizacion.grid(row=3, column=3, padx=0, pady=0) scrollbar_y = ttk.Scrollbar(ventana, orient="vertical", command=tree.yview) scrollbar_x = ttk.Scrollbar(ventana, orient="horizontal", command=tree.xview) tree.configure(yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set) # Ajustar el Treeview al contenido de la ventana tree.pack(fill="both", expand=True) scrollbar_y.pack(side="right", fill="y") scrollbar_x.pack(side="bottom", fill="x") ventana.mainloop()
解决方案
要实现双击Treeview行填充Entry的功能,需要完成三个核心步骤:
1. 声明全局变量让事件函数访问Entry控件
因为双击事件处理函数需要修改Entry的内容,需将EntryNumeroPoliza和EntryNroCotizacion声明为全局变量(适合初学者快速实现,也可使用类封装优化)。
2. 编写双击事件处理函数
创建函数获取Treeview选中行的目标字段值,清空Entry原有内容后填充新数据,避免残留旧内容。
3. 为Treeview绑定双击事件
使用tree.bind("<Double-1>", 事件函数)绑定鼠标左键双击事件。
修改后的完整代码
import tkinter as tk from tkinter import ttk from tkcalendar import DateEntry from tree_data import cargaDatos, obtener_fechas def on_tree_double_click(event): # 获取选中的行 selected_item = tree.selection()[0] # 获取该行的所有数据 item_data = tree.item(selected_item, "values") # 填充到Entry控件:NroCotizacion是第4个索引(从0开始),NumeroPoliza是第5个索引 EntryNroCotizacion.delete(0, tk.END) EntryNroCotizacion.insert(0, item_data[4]) EntryNumeroPoliza.delete(0, tk.END) EntryNumeroPoliza.insert(0, item_data[5]) def crearVentana(): global tree, EntryNumeroPoliza, EntryNroCotizacion # 新增Entry的全局声明 ventana = tk.Tk() ventana.title("Ventana PreFactura") ventana.geometry("1200x700") # Obtener las dimensiones de la pantalla screen_width = ventana.winfo_screenwidth() screen_height = ventana.winfo_screenheight() # Calcular la posición de la ventana para que esté centrada window_width = 1200 window_height = 600 x = (screen_width - window_width) // 2 y = (screen_height - window_height) // 2 ventana.geometry(f"{window_width}x{window_height}+{x}+{y}") frame_calendarios = tk.Frame(ventana) frame_calendarios.pack(pady=10) # Título centrado titulo_label = tk.Label(frame_calendarios, text="Este es un título centrado", font=("Helvetica", 16)) titulo_label.grid(row=0, column=1, columnspan=5, pady=10) label_inicio = tk.Label(frame_calendarios, text="Fecha Inicio") label_inicio.grid(row=1, column=1, padx=10, pady=5) cal_inicio = DateEntry(frame_calendarios, date_pattern='dd/mm/yyyy') cal_inicio.grid(row=1, column=2, padx=(0,150), pady=5) label_fin = tk.Label(frame_calendarios, text="Fecha Termino") label_fin.grid(row=1, column=4, padx=(50,0), pady=5) cal_fin = DateEntry(frame_calendarios, date_pattern='dd/mm/yyyy') cal_fin.grid(row=1, column=5, padx=(0,100), pady=5) btn_aceptar = tk.Button(frame_calendarios, text="Buscar Prefactura", command=lambda: obtener_fechas(cal_inicio, cal_fin, tree)) btn_aceptar.grid(row=2, column=1, columnspan=5, pady=10) tree = ttk.Treeview(ventana, columns=("FechaEmision", "FechaTarificacion", "FechaSolicitud", "InicioVigencia", "NroCotizacion","NumeroPoliza", "NumeroCertificado"), show="headings") tree.heading("FechaEmision", text="FechaEmision") tree.heading("FechaTarificacion", text="FechaTarificacion") tree.heading("FechaSolicitud", text="FechaSolicitud") tree.heading("InicioVigencia", text="InicioVigencia") tree.heading("NroCotizacion", text="NroCotizacion") tree.heading("NumeroPoliza", text="NumeroPoliza") tree.heading("NumeroCertificado", text="NumeroCertificado") tree.pack(fill="both", expand=True) # 绑定双击事件 tree.bind("<Double-1>", on_tree_double_click) lblNumeroPoliza = tk.Label(frame_calendarios, text="Numero Poliza") lblNumeroPoliza.grid(row=3, column=0, padx=10, pady=5) EntryNumeroPoliza = tk.Entry(frame_calendarios) EntryNumeroPoliza.grid(row=3, column=1, padx=10, pady=5) lblNroCotizacion = tk.Label(frame_calendarios, text="Numero Cotizacion") lblNroCotizacion.grid(row=3, column=2, padx=0, pady=0) EntryNroCotizacion = tk.Entry(frame_calendarios) EntryNroCotizacion.grid(row=3, column=3, padx=0, pady=0) scrollbar_y = ttk.Scrollbar(ventana, orient="vertical", command=tree.yview) scrollbar_x = ttk.Scrollbar(ventana, orient="horizontal", command=tree.xview) tree.configure(yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set) # Ajustar el Treeview al contenido de la ventana tree.pack(fill="both", expand=True) scrollbar_y.pack(side="right", fill="y") scrollbar_x.pack(side="bottom", fill="x") ventana.mainloop()
关键说明
tree.selection()[0]:获取当前选中的第一行(Treeview支持多选,此处取第一个选中项)。tree.item(selected_item, "values"):获取选中行的所有字段值,返回元组,索引对应Treeview定义的列顺序。Entry.delete(0, tk.END):清空Entry原有内容,确保新数据不会与旧内容叠加。tree.bind("<Double-1>", on_tree_double_click):绑定鼠标左键双击事件到处理函数。
内容的提问来源于stack exchange,提问作者Juan Ahumada
相关产品推荐
相关产品推荐

