为什么我的ttk.Treeview单击处理程序在tree.focus()上返回错误的项目? [英] Why does my ttk.Treeview click handler return the wrong item on tree.focus()?

查看:245
本文介绍了为什么我的ttk.Treeview单击处理程序在tree.focus()上返回错误的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用ttk.Treeview实例的简单脚本,该实例填充了文件系统树的内容.我想在单击(叶子)项目时执行某种操作,所以我像这样配置了处理程序:

I have a simple script using a ttk.Treeview instance that I'm populating with the contents of a file system tree. 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)

在方法onClick中,我只是打印出被单击的项目,就像这样:

In the method onClick I am simply printing out the item that was clicked, like so:

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

我发现这些消息使点击次数落后了一个.因此,我的第一次单击将获得一个随机值(看起来像树的根),然后第n次单击将打印出被单击的第(n-1)个项目的值.

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.

它们的插入方式如下: tree.insert(parent_id, 'end', id, text=id, tags=['#entry'])

They were inserted like so: tree.insert(parent_id, 'end', id, text=id, tags=['#entry'])

有人知道这是Tkinter中的错误还是我做错了什么?

Anyone know if this is a bug in Tkinter or something that I'm doing wrong?

在Ubuntu Natty以及OS X Lion(使用默认的预安装版本的Python和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)

推荐答案

这是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.

这篇关于为什么我的ttk.Treeview单击处理程序在tree.focus()上返回错误的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆