如何禁用手动调整 Tkinter 的 Treeview 列的大小? [英] How to disable manual resizing of Tkinter's Treeview column?
问题描述
由于
注意列标题的大小.
用户可以拖动鼠标来调整列的大小.我想禁用它.
将 minwidth
设置为某个值可以防止列缩小,但仍然可以将其调整为更大的宽度.我想我可以对更改的宽度做出反应并将其恢复为原始状态,但必须有更好的方法来做到这一点.
以下仅在 Windows 上测试过,其他操作系统可能有所不同.
对于任何未来的读者,从 Tk 8.5 开始,Treeviews 有一个 identify_region
方法,该方法接受屏幕位置 (x,y) 并返回与这些坐标占据的树视图区域相对应的字符串.
返回值之一是分隔符".
我已经用它来捕获分隔符上的双击事件以自动调整列大小,但您也可以使用它来捕获单击事件并阻止它们.
例如:
def handle_click(event):如果 treeview.identify_region(event.x, event.y) == "separator":返回休息"#...treeview.bind('', handle_click)
这具有不禁用整个树视图的优点——因此您仍然可以选择/展开/折叠行、单击列标题进行排序等——您将无法调整列的大小.
请注意,即使禁用调整大小,双箭头"光标 (⇔) 仍会出现.您还可以通过对 <Motion>
事件执行完全相同的操作来防止双箭头光标显示(绑定到它,检查它是否在分隔符上方,并阻止事件被传播)返回字符串 "break"
).
Since I can't horizontally scroll Treeview column due to what appears to be Tk/Tkinter limitation, I want to make it sticky so it is attached to the frame.
The issue is that user can manually resize Treeview column which can mess up my interface in a certain way. Is it possible to disable such functionality?
Note the size of the column header.
User can drag mouse to resize column. I want to disable this.
Setting minwidth
to a certain value prevents column from shrinking, but it is still possible to resize it to a larger width. I suppose I can react to changing width and just revert it to original, but there has to be a better way to do it.
The following has only been tested on Windows, other OS's may vary.
For any future readers, since Tk 8.5, Treeviews have an identify_region
method that accepts a screen position (x,y) and will return a string corresponding to the region of the treeview those coordinates occupy.
One of the return values is "separator".
I've used this to catch double-click events on the separator to auto-size columns, but you could also use it to catch single-click events and block them.
For example:
def handle_click(event):
if treeview.identify_region(event.x, event.y) == "separator":
return "break"
#...
treeview.bind('<Button-1>', handle_click)
This has the advantage of not rendering the entire treeview disabled -- so you can still select/expand/collapse rows, click column headings to sort, etc -- you just won't be able to resize the columns.
Note that even though resizing is disabled, the "double arrow" cursor (⇔) will still appear. You could additionally prevent the double arrow cursor from showing by doing the exact same thing with the <Motion>
event (binding to it, checking if it's above a separator, and stopping the event from being propagated by returning the string "break"
).
>>> sys.version
'3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)]'
>>> tkinter.TkVersion
8.6
这篇关于如何禁用手动调整 Tkinter 的 Treeview 列的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!