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

如何获取Tkinter Treeview组件的列宽?

获取ttk.Treeview所有列宽的方法

要获取Treeview所有列的当前宽度,可通过Treeview的column()方法实现——传入列名并指定option='width',就能获取对应列的实时宽度值。结合你的需求,修改代码如下:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("Minimal Treeview")

treeview = ttk.Treeview(
    root,
    columns=["col1", "col2", "col3"],
    height="10")
treeview.column(0, width=300, anchor="w")
treeview.column(1, width=500, anchor="w")
treeview.column(2, width=60, anchor="w")
treeview.pack()

def on_exit(event):
    # 获取所有列:默认树形列(#0) + 自定义列
    all_columns = ['#0'] + treeview['columns']
    # 遍历收集每列当前宽度
    column_widths = [treeview.column(col, option='width') for col in all_columns]
    print("当前列宽列表:", column_widths)
    # 此处可添加保存逻辑,比如写入本地配置文件
    # 示例:用JSON保存
    # import json
    # with open("treeview_col_widths.json", "w") as f:
    #     json.dump(column_widths, f)
    print("Exit Program")

root.bind("<Destroy>", on_exit)
root.mainloop()

关键说明

  • treeview['columns']返回你定义的自定义列列表,默认的树形列需手动补充#0
  • treeview.column(col, option='width')会返回列的实时宽度,包含用户手动调整后的数值
  • 重启程序时,只需读取保存的宽度值,再调用treeview.column(col, width=xxx)即可恢复列宽设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:16:05