Treeview and Tkinter delete unselected items in treeview

233 views Asked by At

Hi I need to delete all items in Treeview BUT leave searched items in the window. Any help please. At the moment the searched item is highlighted.

####################################################################################################################################################################################################

#ADD LISTBOX
def excel_list():
    file ='ddata.xlsx'
    listy=Toplevel()
    listy.title("EXCEL JOB DATA")
    listy.geometry("1000x500")
    df = pd.read_excel(file)

#CREATE TREEVIEW FRAME
    my_frame = Frame(listy)
    my_frame.pack(pady= 20)
    tree_scroll = Scrollbar(my_frame)
    tree_scroll.pack(side=RIGHT,fill=Y)
    my_tree = ttk.Treeview(my_frame,yscrollcommand=tree_scroll.set)
    my_tree['column']=list(df.columns)
    my_tree['show'] = 'headings'

    for column in my_tree['column']:
        my_tree.heading(column,text=column)

    df_rows = df.to_numpy().tolist()
    for row in df_rows:
        my_tree.insert('','end',values=row) 

    my_tree.pack()
    tree_scroll.config(command=my_tree.yview)



    def search_records():
        
        lookup_record = search_entry.get()
        selections = []
        print(lookup_record)
        for record in my_tree.get_children():
            
                  
            
            if lookup_record in my_tree.item(record)['values']:
                
                selections.append(record)
                
            my_tree.selection_set(selections)
1

There are 1 answers

2
acw1668 On

If you want to delete items not satisfying the search input, just call my_tree.delete(...) on those items:

def search_records():
    lookup_record = search_entry.get()
    for record in my_tree.get_children():
        if lookup_record not in my_tree.item(record)['values']:
            my_tree.delete(record)