sfb
sfb

Reputation: 51

Tk Treeview Focus(). How do I Get Multiple Selected Lines?

ttk.treeview.focus() returns the iid of a single line. The treeview box allows you to select multiple lines. How do I get a list of iids for the selected lines?

Upvotes: 4

Views: 7965

Answers (2)

ViG
ViG

Reputation: 1868

ttk.treeview.focus() returns the current focus item. That means the item that was last selected. The function you are looking for is ttk.treeview.selection(). This returns a tuple of the selected items.

Upvotes: 10

progmatico
progmatico

Reputation: 4964

Use ttk.treeview.selection().

It gives the selected items. See also other Treeview methods with selection prefix such as,

selection_add
selection_remove
selection_toggle

See the example below:

import tkinter as tk
from tkinter import ttk, Tk


def insert(tree, value):
    tree.insert('', tk.END, value, text=value)

root = Tk()
tree = ttk.Treeview(root)

insert(tree, '1')
insert(tree, '2')
insert(tree, '3')

tree.pack()
children = tree.get_children() 
tree.selection_set(children)
tree.selection_toggle(children[1])

# uncomment line by line to see the change
#tree.selection_toggle(children)
#tree.selection_remove(children[1])

print(tree.selection())

root.mainloop()

Upvotes: 6

Related Questions