【问题标题】:How can I add a column to a Tkinter TreeView widget?如何向 Tkinter TreeView 小部件添加列?
【发布时间】:2017-08-25 19:45:01
【问题描述】:

在创建 Tkinter TreeView 小部件后,我需要向它添加新列,但我找不到方法。我尝试使用configure 方法来修改树的列属性,但这会重置除图标列之外的所有列。

我看到的唯一解决方案是将其配置为包含尽可能多的列,并使它们全部不可见,以便在需要添加时使它们可见。有没有更好的办法?

【问题讨论】:

    标签: python tkinter treeview


    【解决方案1】:

    这里的新手: 我和你有同样的问题。我解决了它如下。

    提示:在列名可用后初始化 Treeview。在 Treeview 初始化完成后,我在网络上找不到任何添加新列的解决方案。

    示例: --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)
    

    【讨论】:

      【解决方案2】:

      所有的魔法都在 add_columns 方法中,剩下的只是获得一个工作示例。 我希望这能回答您的问题(有点晚,但可能对其他人有所帮助)。

      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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-06
        • 2016-07-07
        • 2011-04-13
        • 1970-01-01
        • 2011-05-09
        • 2022-01-03
        • 1970-01-01
        相关资源
        最近更新 更多