简体   繁体   English

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

[英]Why does my ttk.Treeview click handler return the wrong item on tree.focus()?

I have a simple script using a ttk.Treeview instance that I'm populating with the contents of a file system tree. 我有一个简单的脚本使用ttk.Treeview实例,我正在填充文件系统树的内容。 I want to perform a certain operation when (leaf) items are clicked so I configured a handler like so: 我想在点击(叶子)项目时执行某个操作,所以我配置了一个像这样的处理程序:

self.tree.tag_bind('#entry', '<1>', self.onClick)

In the method onClick I am simply printing out the item that was clicked, like so: onClick方法中,我只是打印出被点击的项目,如下所示:

def onClick(self, event):
    item_id = str(self.tree.focus())
    print 'Selected item was %s' % item_id
    item = self.tree.item(item_id)
    flag = '#another_tag' in item['tags']
    print '  flag = %s' % flag

I'm finding that the messages are lagging the clicks by one. 我发现这些消息滞后于一个点击。 So my first click gets a random value (looks like the root of the tree), and then the n-th click prints out the values for the (n-1)th item that was clicked. 所以我的第一次点击获得一个随机值(看起来像树的根),然后第n次点击打印出被点击的第(n-1)项的值。

They were inserted like so: tree.insert(parent_id, 'end', id, text=id, tags=['#entry']) 它们是这样插入的: tree.insert(parent_id, 'end', id, text=id, tags=['#entry'])

Anyone know if this is a bug in Tkinter or something that I'm doing wrong? 任何人都知道这是Tkinter中的错误还是我做错了什么?

This appears to be an issue on both Ubuntu Natty as well as OS X Lion (using the default pre-installed versions of Python and Tkinter) 这似乎是Ubuntu Natty和OS X Lion的一个问题(使用默认的预装版本的Python和Tkinter)

This is the way Tkinter is designed to work. 这就是Tkinter的工作方式。 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. 它是widget组中设置所选项的绑定。 This makes it really easy to override the default bindings, at the expense of making it slightly harder to augment default bindings. 这使得覆盖默认绑定非常容易,但代价是增加默认绑定会稍微困难一些。

This has been asked a few times on this site. 在本网站上已经多次询问过这个问题。 Search for "bindtags" on this site; 在此网站上搜索“bindtags” ; bindtags are the mechanism that controls the order of event processing. bindtags是控制事件处理顺序的机制。

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. 在树视图小部件的特定情况下,我建议绑定到<<TreeviewSelect>>事件,该事件将在设置选择后进行处理。 You can then use the tag_has method to determine what sort of node was clicked on. 然后,您可以使用tag_has方法确定单击的节点类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM