'How to deselect an item (or items) of a Tkinter ttk.Treeview?

I'm having trouble trying to deselect a Treeview item while doing it from a callback of another widget. I managed to implement a working deselection on ESCAPE press with:

tree.selection_remove(tree.focus())

in a callback bound to a treeview object itself. It works only when the treeview has focus (but it's OK, that's a desired behavior). On the other hand trying the same from a callback of another widget doesn't work.

I tried using:

tree.selection_clear()

as recommended here, but this does not work either.

Important: selecting items in the treeview from the same call with tree.selection_add(iid) works. The same as manipulating yet another widget (a combobox, and the widget doing the call is a frame). Based on this, I don't suppose the problem is due to some silly bug (a typo or something like that) in my code.

My theory is being out of focus is a problem as it's the only difference I see between when the same code works with ESCAPE but not elsewhere, so I tried to gain focus with tree.focus_set() and tree.focus_force(), but that didn't change anything.

I don't quite understand what selection_clear() is supposed to do. As ttk.Treeview inherits this method from ttk.Misc the documentation on this is scarse. I couldn't find anything on it here or here. The only thing I found is a laconic:

Clear the current X selection.

from the Python shell help (what's the cryptic X, coordinates?)

So how to accomplish so seemingly simple? Please help, I'm at a loss for ideas.



Solution 1:[1]

What about:

for item in self.tree.selection():
   self.tree.selection_remove(item)

Solution 2:[2]

The answer that z33k gave helped me get what I needed. But if multiple items are selected it will only deselect the first one. To deselect all items that are currently selected I used

This logic is identical to est.tenorio, just with an explanation of what it its doing.

Deselect all items

for i in tree.selection():
        tree.selection_remove(i)

Solution 3:[3]

If you want it to be done in one line.

tree.selection_remove(*tree.selection())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 est.tenorio
Solution 2
Solution 3 Ghanteyyy