Search code examples
pythontkintertreeview

How to GET the column width in a Tkinter Treeview


Is there a way to get the width of all treeview columns of a tk.treeview?

I know how to set the width, but I would like to save the user's custom changes in a list after they exit the window so I can recall it after a restart.

So far I have everything running, I'm just searching (and couldn't find) an answer on how to get the column width.

Here's a minimal code example:

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):
    # Desired code:
    # column_width = treeview.columnswidth
    # column_width holds something like [233, 500, 48]
    print("Exit Program")


# Before exiting, user changes the column width manually with the mouse
root.bind("<Destroy>", on_exit)
root.mainloop()

Every help is appreciated! :-) Thank you very much in advance and enjoy your coding.


Solution

  • Simply call the column() with the column name and the option 'width'

    print(treeview.column('col1', 'width'))
    
    # => 300 (returns the column width as an integer)
    

    Update: The error you're getting is caused because the treeview widget is destroyed before you can call column() - see below for a fix

    # modify the 'on_exit' function as follows
    def on_exit():  # no event binding means no 'event' param
        print(treeview.column('col1', 'width'))  # get col width as needed
        # put whatever else you want to do before exiting here...
        print('Exit Program')
        root.quit()  # exit
    
    
    # replace the event binding with this protocol handler
    root.protocol('WM_DELETE_WINDOW', on_exit)
    root.mainloop()
    

    The protocol handler 'WM_DELETE_WINDOW' is called whenever the window it's bound to is destroyed. In this case, it will call your on_exit function when you attempt to close the window. You will still need to explicitly quit the program, so that's also handled in on_exit with root.quit()