python tkinter中treeview双击列表可修改列值

效果如下图:

python tkinter中treeview双击列表可修改列值_第1张图片

import tkinter as tk
from tkinter import ttk

def set_cell_combobox(event, value):
    def change_value(_):
        combobox.destroy()
        old_value[col] = combobox_var.get()
        tree.item(row, value=old_value)

    def leave(e):
        """当鼠标点击combobox的箭头时,也被认为是离开控件,所以要对离开事件进行区分"""
        if e.state == 8:
            combobox.destroy()
        else:
            combobox.unbind('')

    def focusout(_):
        """当combobox的列表被打开,并且没有选取任何选项,此时光标会自动回到combobox控件,可以利用combobox的这个特性,当光标回到控件时,自动获得此方法"""
        combobox.bind('', lambda _: combobox.destroy())

    column = tree.identify_column(event.x)
    row = tree.identify_row(event.y)
    col = int(column.split('#')[1]) - 1
    old_value = list(tree.item(row, 'value'))
    print(column,row,col,old_value)
    cell_coord = tree.bbox(row, column=column)
    print(cell_coord)
    combobox_var = tk.StringVar()
    combobox = ttk.Combobox(tree, width=int(cell_coord[2] / 7) - 2, textvariable=combobox_var)
    combobox['value'] = value
    combobox.place(x=cell_coord[0] - 2, y=cell_coord[1], anchor='nw')
    combobox.insert(0, old_value[col])
    combobox.focus_set()
    combobox.bind('<>', change_value)
    combobox.bind('', leave)
    combobox.bind('', focusout)

root=tk.Tk()
tree = ttk.Treeview(root, show='headings')
tree['columns'] = ['A', 'B', 'C']
tree.heading('#1', text='A')
tree.heading('#2', text='B')
tree.heading('#3', text='C')
tree.insert('', 'end', text='第一行', value=['1','2','3'])
tree.insert('', 'end', text='第二行', value=['2','3','4'])
value_l=['a','b','c']
tree.bind('', lambda event:set_cell_combobox(event, value=value_l))
tree.pack()
root.mainloop()

你可能感兴趣的:(python)