You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在自定义tkinter TreeView类中正确设置列数与列名

TreeView自定义列时多列问题的解决办法

问题场景

自定义tkinter的TreeView类,调用create_columns方法设置列数时,总是会多显示一列。相关代码如下:

import tkinter
from tkinter import ttk

class TableTreeView (ttk.TreeView):
    def __init__(self, root):
        super().__init__(root)

    def create_columns(self, columns_count):
        columns_names = []
        for i in range(columns_count):
            columns_names.append('№'+str(i+1))
        columns_names = tuple(columns_names)
        self['columns'] = columns_names
        for i in range(columns_count):
            self.heading(columns_names[i], text=columns_names[i])

root = tkinter.Tk()
table = TableTreeView(root)
table.create_columns(2)
table.pack()
root.mainloop()

尝试过用self.config({"columns": columns_names})替代self['columns'] = columns_names,问题依然存在。

原因分析

ttk.TreeView默认自带一个树形结构专用列(内部标识为#0),该列默认处于显示状态。当你设置2个自定义列时,加上这个默认列,最终就会显示3列。

解决办法

有两种可行的处理方式:

方式一:初始化时指定只显示自定义表头列

修改TreeView的初始化参数,添加show="headings",直接隐藏默认的树形列,只显示自定义列:

import tkinter
from tkinter import ttk

class TableTreeView (ttk.TreeView):
    def __init__(self, root):
        # 指定show="headings",仅展示自定义列的表头
        super().__init__(root, show="headings")

    def create_columns(self, columns_count):
        columns_names = [f'№{i+1}' for i in range(columns_count)]
        self['columns'] = tuple(columns_names)
        for col in columns_names:
            self.heading(col, text=col)

root = tkinter.Tk()
table = TableTreeView(root)
table.create_columns(2)
table.pack()
root.mainloop()

方式二:隐藏默认列的显示

如果需要保留TreeView的树形结构功能(比如后续要展开/折叠节点),可以将默认列的宽度设为0,视觉上隐藏它:

import tkinter
from tkinter import ttk

class TableTreeView (ttk.TreeView):
    def __init__(self, root):
        super().__init__(root)

    def create_columns(self, columns_count):
        columns_names = [f'№{i+1}' for i in range(columns_count)]
        self['columns'] = tuple(columns_names)
        # 将默认的#0列宽度设为0,禁止拉伸
        self.column("#0", width=0, stretch=False)
        for col in columns_names:
            self.heading(col, text=col)

root = tkinter.Tk()
table = TableTreeView(root)
table.create_columns(2)
table.pack()
root.mainloop()

内容的提问来源于stack exchange,提问作者legion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:00:57