Home > Software design >  Tkinter treeview selection of mutiple rows and retrieve the selected rows
Tkinter treeview selection of mutiple rows and retrieve the selected rows

Time:11-26

I am using the sample Treeview widget for the user to select the multiple rows. I used the tree.selection method for this in the code.

However, I am unable to figure out a better approach to retrieve the selected rows in an appropriate way. For example, If the user selects the IDs with 1 and 2. Then I would like to use the Price ,Items information etc for the different task. If the user selects all the three rows then so on .... Below is the working sample, I tried to split it and saved it in the variables but it will not work if the user select one or two rows ?enter image description here

Thanks.

import tkinter as tk
import tkinter.ttk

def Tree_Focus_Area():
    curItems = tree.selection()
    Var=",".join([str(tree.item(i)['values']) for i in curItems])
    a, b,c,d,e,f,g,h,i,j,k,l = str(Var).split(",")
    print("The selected items for the first ID:", a,b,c,d)
    print("The selected items for the second ID:", e,f,g,h)
    print("The selected items for the second ID:", i,j,k,l)

root = tk.Tk()
tree = tkinter.ttk.Treeview(root, height=4)

tree['show'] = 'headings'
tree['columns'] = ('ID', 'Items', 'Price', 'Priority')
tree.heading("#1", text='ID', anchor='w')
tree.column("#1", stretch="no")
tree.heading("#2", text='Items', anchor='w')
tree.column("#2", stretch="no")
tree.heading("#3", text='Price', anchor='w')
tree.column("#3", stretch="no")
tree.heading("#4", text='Priority', anchor='w')
tree.column("#4", stretch="no")
tree.pack()

tree.insert("", "end", values=["1", "Laptop", "$1000.50", "10"])
tree.insert("", "end", values=["2", "Desktop Equipment", "$800.50", "5"])
tree.insert("", "end", values=["3", "Office Supplies", "$467.50", "7"])

tree.bind("<Return>", lambda e: Tree_Focus_Area())

root.mainloop()

CodePudding user response:

You can simply get the values tuple of the selected rows and append them to a list:

def Tree_Focus_Area():
    selections = tree.selection()
    rows = [tree.item(i, 'values') for i in selections]
    for i, row in enumerate(rows, 1):
        print(f"The selected items for ID #{i}:", ', '.join(row))
  • Related