SlavaCat
SlavaCat

Reputation: 91

Stop tkinter treeivew from deselecting?

I have a treeview and I don't want it to deselect items so easily. I mainly don't want it to deselect everything when I'm trying to expand a parent node.

Is there any way that I can manage treeview deselection with buttons rather than leave it all to the widget?

Upvotes: 0

Views: 322

Answers (1)

acw1668
acw1668

Reputation: 46669

One of the way is:

  • set selectmode='none' to disable selection on mouse left click
  • bind mouse right click to a callback and select the item which is clicked inside the callback.
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

tree = ttk.Treeview(root, selectmode='none')
tree.pack()

# insert dummy data
for i in range(5):
    node = tree.insert('', 'end', text=f'Node {i+1}')
    for j in range(3):
        tree.insert(node, 'end', text=f'Sub-note {i+1}.{j+1}')

def on_right_clicked(event):
    row = tree.identify('row', event.x, event.y)
    if row:
        # select clicked item
        tree.selection_set(row)

tree.bind('<3>', on_right_clicked)

root.mainloop()

Then expanding a parent node does not select the node.


Update: if multiple selections is required, then replace tree.selection_set(...) by tree.selection_toggle(...).

Upvotes: 1

Related Questions