問題描述
我有一個使用 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'])
有人知道這是 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";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() 上返回錯誤的項目?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!