Search code examples
pythonpython-2.7tkintertreeviewtk-toolkit

Get the text of a Tkinter Treeview item using its ID


I would like to get the display text of the treeview item subdir3 when I double click. I know 'text' is not correct as print tree.set('subdir3') prints a dictionary of columns and values and 'text' is not part of that, but I can't find anything about it in the limited documentation I have found.

Here's my code:

from Tkinter import *
import ttk

root = Tk()

def OnDoubleClick(event):
    print tree.set('subdir3')['text']


tree = ttk.Treeview(root)

tree["columns"]=("one","two")
tree.heading("one", text="coulmn A")
tree.heading("two", text="column B")

tree.insert("", 3, "dir3", text="Dir 3",values=("3A"," 3B"))
tree.insert("dir3", 3, 'subdir3', text="sub dir 3", values=("3A"," 3B"))

tree.bind("<Double-1>", OnDoubleClick)


tree.pack()
root.mainloop()

Desired output:

sub dir 3

Solution

  • You can use the identify method to get the item under the cursor, and the item method to get information about that item:

    def OnDoubleClick(event):
        item = tree.identify("item", event.x, event.y)
        print "you clicked on", tree.item(item)["text"]