I\'m just starting with a small tkinter tree program in python 3.4.
I\'m stuck with returning the first value of the row selected. I have multiple r
This is a good example of getting information of a row selected in a python tkinter treeview. Allow me to represent a final neat coding discussed here. I use python 3.8
from tkinter import *
from tkinter import ttk
def selectItem(a):
curItem = tree.focus()
print(tree.item(curItem))
root = Tk()
tree = ttk.Treeview(root, columns=("size", "modified"))
tree["columns"] = ("date", "time", "loc")
tree.column("date", width=65)
tree.column("time", width=40)
tree.column("loc", width=100)
tree.heading("date", text="Date")
tree.heading("time", text="Time")
tree.heading("loc", text="Loc")
tree.bind('<ButtonRelease-1>', selectItem)
tree.insert("","end",text = "Name",values = ("Date","Time","Loc"))
tree.grid()
root.mainloop()
Ther result is
{'text': 'Name', 'image': '', 'values': ['Date', 'Time', 'Loc'], 'open': 0, 'tags': ''}
You can copy, paste and try it. It's good.
To get the selected item and all its attributes and values, you can use the item
method:
def selectItem(a):
curItem = tree.focus()
print tree.item(curItem)
This will output a dictionary, from which you can then easily retrieve individual values:
{'text': 'Name', 'image': '', 'values': [u'Date', u'Time', u'Loc'], 'open': 0, 'tags': ''}
Also note that the callback will be executed before the focus in the tree changed, i.e. you will get the item that was selected before you clicked the new item. One way to solve this is to use the event type ButtonRelease
instead.
tree.bind('<ButtonRelease-1>', selectItem)