25

I'm creating a GUI with Tkinter, and a major part of the GUI is two Treeview objects. I need the contents of the Treeview objects to change when an item (i.e. a directory) is clicked twice.

If Treeview items were buttons, I'd just be able to set command to the appropriate function. But I'm having trouble finding a way to create "on_click" behavior for Treeview items.

What Treeview option, method, etc, enables me to bind a command to particular items and execute that command "on_click"?

nbro
  • 15,395
  • 32
  • 113
  • 196
Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151

4 Answers4

46

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 tk
from tkinter import ttk

class 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()
nbro
  • 15,395
  • 32
  • 113
  • 196
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
26

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 tk
import tkinter.ttk as ttk

class 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()
nbro
  • 15,395
  • 32
  • 113
  • 196
Csaba
  • 261
  • 3
  • 2
4

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])
0

I was having a similar functionality on a Treeview and overcome the issue with row selection on click by binding the event to be on click release. As you will have to release your click eventually :P my code looks like something below:

from tkinter import *
from tkinter import ttk

<codehere>

TreeView.bind('<Double-1>', function1) # If you want bind function1 on double click
    
TreeView.bind('<ButtonRelease-1>', myfunction2) # If you want bind function2 on single click (on release click)
Omar Mughrabi
  • 113
  • 1
  • 3