Home > Net >  selecting mutliple items in python Tkinter Treeview with mouse event Button-1
selecting mutliple items in python Tkinter Treeview with mouse event Button-1

Time:11-20

I looked for and tested many similar questions/answers/possible duplicates here on SO and other sites but I'm interested specifically in using the solution below for simplicity's sake and minimal reproducible example constraint satisfaction.

Why does the following modification of this previous answer's code does not work/how to make it work?

import tkinter as tk
from tkinter import ttk
 
root = tk.Tk()
 
tree = ttk.Treeview(root)
tree.pack(fill="both", expand=True)
 
items = []
for i in range(10):
    item = tree.insert("", "end", text="Item {}".format(i 1))
    items.append(item)
 
items_to_select = items[:]
 
 
def select_all_items(event):
    tree.selection_set(items_to_select)
 
tree.bind('<Button-1>', select_all_items)
 
 
root.mainloop()

The original answer works as is.

I'm looking for a way to make it work with mouse event Button-1 click. The result should execute the selection of all items in the treeview when users click on any one item with the left mouse button (Button-1).

CodePudding user response:

Since the default action of a mouse click on any row of the treeview will clear previous selections and select the clicked row.

To disable the default action, return "break" from the callback:

def select_all_items(event):
    tree.selection_set(items)
    return "break"

Then clicking any row in the treeview will select all rows in it.

Note that you can use items directly and don't need to clone it to new variable.

CodePudding user response:

Try this:

import tkinter as tk
from tkinter import ttk
 
root = tk.Tk()
 
tree = ttk.Treeview(root)
tree.pack(fill="both", expand=True)
 
items = []
for i in range(10):
    item = tree.insert("", "end", text="Item {}".format(i 1))
    items.append(item)
 
#items_to_select = []
    
for item in items:
    tree.insert('', tk.END, values=item) 
 
def select_all_items(event):
    for selected_item in tree.selection():
        item = tree.item(selected_item)
        print(item)
    #tree.selection_set(items_to_select)
 
tree.bind('<Button-1>', select_all_items)
  
root.mainloop()

You can also substitute for code. return "break" I commented out line 14.

import tkinter as tk
from tkinter import ttk
 
root = tk.Tk()
 
tree = ttk.Treeview(root)
tree.pack(fill="both", expand=True)
 
items = []
for i in range(10):
    item = tree.insert("", "end", text="Item {}".format(i 1))
    items.append(item)
 
#items_to_select = []
    
for item in items:
    tree.insert('', tk.END, values=item) 
 
def select_all_items(event):
     tree.selection_set(items)
     return "break"
 
tree.bind('<Button-1>', select_all_items)
  
root.mainloop()
  • Related