简体   繁体   English

如何将列添加到 Tkinter TreeView 小部件?

[英]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.创建 Tkinter TreeView 小部件后,我需要将新列添加到它,但我找不到方法。 I've tried using the configure method to modify the columns attribute of the tree, but this resets all columns except the icon column.我已经尝试使用configure方法来修改树的列属性,但这会重置除图标列之外的所有列。

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.提示:在列名可用后初始化 Treeview。 I couldn't find any solution on the web to add new columns after the initialisation of the Treeview is done.在完成 Treeview 的初始化后,我在网络上找不到任何添加新列的解决方案。

Example: --blah bhah code---示例:--blah bhah 代码---

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.所有的魔法都在 add_columns 方法中,剩下的就是获取一个工作示例。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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