Automatic minimum width for column '#0' in

2019-08-22 15:54发布

The tkinter.TreeView has a first default column (identifier #0). For example this is for holding the '+' sing of the tree.

When I add other columns this first column is resized and much to wide.

enter image description here

This is the code producing this treeview.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from tkinter import *
from tkinter import ttk

root = Tk()

tree = ttk.Treeview(root, columns=('one'))
idx = tree.insert(parent='', index=END, values=('AAA'))
tree.insert(parent=idx, index=END, values=('child'))

tree.column('#0', stretch=False)  # NO effect!

tree.pack()
root.mainloop()

I would like to have the first column (#0) in a minimum fixed width depending on the + sign in there. The point is that the width for that column differs from system to system because of different desktop environments and user settings. So it would break the plattform independence of Python3 and Tkinter when I would set a fixed size in pixel here.

1条回答
再贱就再见
2楼-- · 2019-08-22 16:18

On windows that expand / collapse button seems to be dynamically drawn based on the size, and according to this minwidth option defaults to 20. I'd write a method to calculate minwidth such that it accounts for the depth and image and text width + 20.

That being said, using this answer a method can be written for fixing the column width at the minwidth Tk defaults to, by breaking the tagbind at that exact location:

#the minimum width default that Tk assigns
minwidth = tree.column('#0', option='minwidth')

tree.column('#0', width=minwidth)

#disabling resizing for '#0' column particularly
def handle_click(event):
    if tree.identify_region(event.x, event.y) == "separator":
        if tree.identify_column(event.x) == '#0':
            return "break"

#to have drag drop to have no effect
tree.bind('<Button-1>', handle_click)
#further disabling the double edged arrow display
tree.bind('<Motion>', handle_click)

And a complete example:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from tkinter import *
from tkinter import ttk

root = Tk()

tree = ttk.Treeview(root, columns=('one'))
idx = tree.insert(parent='', index=END, values=('AAA'))
tree.insert(parent=idx, index=END, values=('child'))

tree.column('#0', stretch=False)  # NO effect!

#the minimum width default that Tk assigns
minwidth = tree.column('#0', option='minwidth')

tree.column('#0', width=minwidth)

#disabling resizing for '#0' column particularly
def handle_click(event):
    if tree.identify_region(event.x, event.y) == "separator":
        if tree.identify_column(event.x) == '#0':
            return "break"

#to have drag drop to have no effect
tree.bind('<Button-1>', handle_click)
#further disabling the double edged arrow display
tree.bind('<Motion>', handle_click)

tree.pack()
root.mainloop()
查看更多
登录 后发表回答