Command for clicking on the items of a Tkinter Treeview widget? Command for clicking on the items of a Tkinter Treeview widget? tkinter tkinter

Command for clicking on the items of a Tkinter Treeview widget?


If you want something to happen when the user double-clicks, add a binding to "<Double-1>". Since a single click sets the selection, in your callback you can query the widget to find out what is selected. For example:

import tkinter as tkfrom tkinter import ttkclass App:    def __init__(self):        self.root = tk.Tk()        self.tree = ttk.Treeview()        self.tree.pack()        for i in range(10):            self.tree.insert("", "end", text="Item %s" % i)        self.tree.bind("<Double-1>", self.OnDoubleClick)        self.root.mainloop()    def OnDoubleClick(self, event):        item = self.tree.selection()[0]        print("you clicked on", self.tree.item(item,"text"))if __name__ == "__main__":    app = App()


The previous solution fails when multiple elements are selected and the user uses SHIFT+CLICK (at least on a Mac).

Here is a better solution:

import tkinter as tkimport tkinter.ttk as ttkclass App:    def __init__(self):        self.root = tk.Tk()        self.tree = ttk.Treeview()        self.tree.pack()        for i in range(10):            self.tree.insert("", "end", text="Item %s" % i)        self.tree.bind("<Double-1>", self.OnDoubleClick)        self.root.mainloop()    def OnDoubleClick(self, event):        item = self.tree.identify('item',event.x,event.y)        print("you clicked on", self.tree.item(item,"text"))if __name__ == "__main__":    app = App()


I know this is old but this code will also print multiple selected item in a treeview.

def on_double_click(self, event):    item = self.tree.selection()    for i in item:        print("you clicked on", self.tree.item(i, "values")[0])