5

I have a Treeview in tkinter (Python 3.6 on Linux, but the same happens on windows) which I'm using to emulate a sort of spread-sheet layout. My problem is that, if I run the example code, below, and resize say "Column 1" then as "Column 1" gets bigger, "Column 2" gets smaller. However, if I drag out the final column to the right, the scroll bar expands, and now I can resize column 1 without changing the size of column 2 (instead the whole tree view expands). If you then resize, say, column 1 again, until all columns fit in the view, the behaviour seems to revert to the original.

What causes this change of behaviour? Both, how can I stop it, and how can I ensure it's the default?

Minimal working example:

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

tree = ttk.Treeview(root)
tree["show"] = "headings"
tree["columns"] = list(range(3))
for i in range(3):
    tree.heading(i, text="Column {}".format(i))

for i in range(5):
    tree.insert('', "end", i)

tree.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))
xs = ttk.Scrollbar(root, orient=tk.HORIZONTAL, command=tree.xview)
tree["xscrollcommand"] = xs.set
xs.grid(row=1, column=0, sticky=(tk.E, tk.W))

root.mainloop()

1 Answer 1

8

The best control you have in a Treeview is using the stretch attribute of columns. If you make all of your columns' stretch and minwidth attributes.

for i in range(3):
    tree.column('#' + str(i), minwidth=300, stretch=0)
    tree.heading(i, text="Column {}".format(i))
tree.column('#0', stretch=0)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! So stretch=False works well for me: it forces the widget into the "2nd mode" I discussed in the OP. Official docs: docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview Still leaves it slightly unclear why, by default, the widget sometimes resizes the columns. But such is life...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.