简体   繁体   中英

How can I add a column to a Tkinter TreeView widget?

I need to add new columns to a Tkinter TreeView widget after creating it, but I can't find a way to do it. I've tried using the configure method to modify the columns attribute of the tree, but this resets all columns except the icon column.

The only solution I see is to configure it to have as many columns as I can possibly need and make them all invisible, so that I can make them visible when I need to add one. Is there a better way?

Newbie here: I had same issue as you. I solved it as below.

hint: Initialise the Treeview 'after' you have your column names available. I couldn't find any solution on the web to add new columns after the initialisation of the Treeview is done.

Example: --blah bhah code---

def treecols(self,colnames=[],rowdata=[]):
    self.tree = ttk.Treeview ( self.frame1,columns=colnames )
    self.tree.grid ( )

    for eachcol in colnames:
        self.tree.heading(column=eachcol,text=eachcol)
        self.tree.column(column=eachcol,width=100,minwidth=0)

All the magic is in the add_columns method, the rest is just get a working example. I hope this answers your question (a bit late but it might help others).

import tkinter
import tkinter.ttk

class GUI():
    def __init__(self, master):
        self.view = tkinter.ttk.Treeview(master)
        self.view.pack()
        self.view.heading('#0', text='Name')
        
        self.view.insert('', 'end', text='Foo')
        self.view.insert('', 'end', text='Bar')
        self.view['columns'] = ('foo')
        self.view.heading('foo', text='foo')
        self.view.set(self.view.get_children()[0], 'foo', 'test')
        self.add_columns(('bar', 'blesh'))

    def add_columns(self, columns, **kwargs):
        # Preserve current column headers and their settings
        current_columns = list(self.view['columns'])
        current_columns = {key:self.view.heading(key) for key in current_columns}

        # Update with new columns
        self.view['columns'] = list(current_columns.keys()) + list(columns)
        for key in columns:
            self.view.heading(key, text=key, **kwargs)

        # Set saved column values for the already existing columns
        for key in current_columns:
            # State is not valid to set with heading
            state = current_columns[key].pop('state')
            self.view.heading(key, **current_columns[key])
            

tk = tkinter.Tk()
GUI(tk)
tk.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM