Search code examples
pythontkintertreeview

Row selection in treeview


Every time as the row updates the following code select all the row.

child_id =treeview.get_children()
treeview.selection_set(child_id)

Can't i just select the particular row using control and everytime only the selected row get selects again

Sample code:

from tkinter import ttk
import tkinter
import threading

def main():
    root = tkinter.Tk()
    
    ccols = ('num1','num2')
    treeview = ttk.Treeview(root, columns=ccols)
    for col in ccols:
        treeview.heading(col, text=col)
    treeview.grid(row=8, column=0)
    
    def sample():
       for i in range(50):
           treeview.delete(*treeview.get_children()) 
           a=(treeview.insert("","end",values=(i,0)))
           a=(treeview.insert("","end",values=(i,0)))
           a=(treeview.insert("","end",values=(i,0)))
           
           child_id =treeview.get_children()
           treeview.selection_set(child_id)
               
       threading.Timer(4.0, sample).start()

    sample()
    root.mainloop()


if __name__ == '__main__':
    main()

Solution

  • You can save the current indexes of the selected rows. Then after updating the treeview, get the row IDs by the saved indexes and select the rows using the row IDs:

    def sample():
        # save the indexes of selected rows
        indexes = [treeview.index(id) for id in treeview.selection()]
        # update treeview
        for i in range(50):
            treeview.delete(*treeview.get_children()) 
            treeview.insert("", "end", values=(i,0))
            treeview.insert("", "end", values=(i,0))
            treeview.insert("", "end", values=(i,0))
        # select the rows using the saved indexes
        for idx in indexes:
            child_id = treeview.get_children()[idx]
            treeview.selection_add(child_id)
                   
        threading.Timer(4.0, sample).start()