問(wèn)題描述
我有一個(gè)使用 ttk.Treeview
實(shí)例的簡(jiǎn)單腳本,我用文件系統(tǒng)樹的內(nèi)容填充該實(shí)例.我想在單擊(葉)項(xiàng)目時(shí)執(zhí)行某個(gè)操作,所以我配置了一個(gè)處理程序,如下所示:
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
方法中,我只是打印出被點(diǎn)擊的項(xiàng)目,如下所示:
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
我發(fā)現(xiàn)消息比點(diǎn)擊次數(shù)滯后一倍.所以我的第一次點(diǎn)擊會(huì)得到一個(gè)隨機(jī)值(看起來(lái)像樹的根),然后第 n 次點(diǎn)擊會(huì)打印出被點(diǎn)擊的第 (n-1) 個(gè)項(xiàng)目的值.
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'])
有人知道這是 Tkinter 中的錯(cuò)誤還是我做錯(cuò)了什么?
Anyone know if this is a bug in Tkinter or something that I'm doing wrong?
這似乎是 Ubuntu Natty 和 OS X Lion 上的一個(gè)問(wèn)題(使用 Python 和 Tkinter 的默認(rèn)預(yù)安裝版本)
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 設(shè)計(jì)的工作方式.小部件上的綁定在小部件類上的綁定之前處理.設(shè)置所選項(xiàng)目的是小部件類上的綁定.這使得覆蓋默認(rèn)綁定變得非常容易,但代價(jià)是增加默認(rèn)綁定變得更加困難.
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.
這個(gè)網(wǎng)站已經(jīng)被問(wèn)過(guò)幾次了.在本站搜索bindtags";bindtags 是控制事件處理順序的機(jī)制.
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>>
事件,該事件將在設(shè)置選擇后處理.然后,您可以使用 tag_has
方法來(lái)確定單擊了哪種節(jié)點(diǎn).
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.
這篇關(guān)于為什么我的 ttk.Treeview 點(diǎn)擊處理程序在 tree.focus() 上返回錯(cuò)誤的項(xiàng)目?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!