Why is my ttk.Treeview click handler returning the wrong element in tree.focus ()?

I have a simple script using the ttk.Treeview instance, which I populate with the contents of the file system tree. I want to perform a specific operation when the elements are clicked (leaf), so I configured the handler as follows:

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

In the onClick method onClick I just print the element that was clicked, for example:

 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 find that messages delay clicks by one. So my first click gets a random value (looks like the root of the tree), and then the nth click displays the values โ€‹โ€‹for the (n-1) th element that was clicked.

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

Does anyone know if this is a bug in Tkinter or something that I am doing wrong?

This seems to be a problem for both Ubuntu Natty and OS X Lion (using pre-installed versions of Python and Tkinter by default)

+6
source share
1 answer

This is how Tkinter works. Widget bindings are processed before bindings in the widget class. These bindings in the widget class define the selected item. This makes it easy to override the default bindings, making it a little harder to increase the default bindings.

This was asked several times on this site. Search for "bindtags" on this site; bindtags is a mechanism that controls the order in which events are processed.

In the specific case of the treeview widget, I recommend that you attach to the <<TreeviewSelect>> event, which will be processed after the selection. Then you can use the tag_has method to determine which type of node was clicked.

+4
source

Source: https://habr.com/ru/post/923211/


All Articles