且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的ttk.Treeview单击处理程序在tree.focus()上返回错误的项目?

更新时间:2023-09-18 17:51:22

这是Tkinter设计的工作方式.在窗口小部件类上进行绑定之前,先处理窗口小部件上的绑定.窗口小部件类上的绑定设置了所选项目.这样一来,覆盖默认绑定就变得非常容易了,但代价是很难增加默认绑定.

This is the way Tkinter is designed to work. Bindings on a widget are processed before bindings on the widget class. It is the bindings on the widget class that set the selected item. This makes it really easy to override the default bindings, at the expense of making it slightly harder to augment default bindings.

这个问题在这个网站上已经被问过几次了. 在此站点上搜索"bindtags" ;绑定标签是控制事件处理顺序的机制.

This has been asked a few times on this site. Search for "bindtags" on this site; bindtags are the mechanism that controls the order of event processing.

在树形视图小部件的特定情况下,我建议绑定到<<TreeviewSelect>>事件,将在设置选择后对其进行处理.然后,您可以使用tag_has方法来确定单击了哪种节点.

In the specific case of the treeview widget, I recommend binding to the <<TreeviewSelect>> event, which will be processed after the selection has been set. You can then use the tag_has method to determine what sort of node was clicked on.