How to get the value of a selected treeview item?

Question:

I’ve looked at several posts regarding this and they’ve done the following

-The output i get is blank

-The output i get is the id, which is practically useless unless somebody can show me how to manipulate it

-No output at all

i just want to be able to click an item in treeview, and instantly be given the text i just clicked

 def OnDoubleClick(event):
        item = course1_assessments.focus()
        print (item)

 course1_assessments.bind("<<TreeviewSelect>>", OnDoubleClick)

This code gives me ‘I001’ if i click the first item, and ‘I002’ when i click the second; id assume these are column values in the tree, but still useless to me

Asked By: Ryan Mansuri

||

Answers:

You can get a list of the selected items with the selection method of the widget. It will return a list of item ids. You can use the item method to get information about each item.

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(side="top", fill="both")
        self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)

        for i in range(10):
            self.tree.insert("", "end", text="Item %s" % i)

        self.root.mainloop()

    def on_tree_select(self, event):
        print("selected items:")
        for item in self.tree.selection():
            item_text = self.tree.item(item,"text")
            print(item_text)

if __name__ == "__main__":
    app = App()
Answered By: Bryan Oakley

I tried this as well to retrieve the ID in one of the columns for use in another function. I noticed when selecting multiple elements, they return the same ID as the last selected when doing mouseclicks combined with SHIFT. Selecting one at a time with mouseclick and CTRL works when printing to console.

I also found that to change output from ID to another column change the value inside square brackets. Combine this with the above answer as needed. To give context of my implementation, I am using the ID returned from the below code to query a database to retrieve the text I want and then outputting that into another frame or textbox widget.

    def db_reader_selector(self, event):
        return print(self.db_reader.selection()[0])

Here’s a dead simple piece of code that I believe answers the question "How do I get a value from a selected Treeview item:’ The tree has columns ‘MTD’ and ‘YTD’. The ‘item’ retrieved by the tree.selection() call is a tuple of strings, the first value being the iid of the selected item. This value is passed to the set method, along with the name of the column value you want to retrieve. All of this seems grossly counter-intuitive to me, but it works.

import tkinter.ttk as ttk


if __name__ == '__main__':
    def tree_select(event):
        tree: ttk.Treeview = event.widget
        item = tree.selection()
        mtd_var.set(tree.set(item[0], 'MTD'))
        ytd_var.set(tree.set(item[0], 'YTD'))
        pass

    iid_map: dict[str, str] = {}
    root = tk.Tk()
    ttk.Label(master=root, text='MTD', width=4, anchor=tk.E).grid(column=0, row=0, padx=5, pady=5)
    mtd_var = tk.StringVar()
    mtd_entry = ttk.Entry(master=root, textvariable=mtd_var, width=10)
    mtd_entry.grid(column=1, row=0, padx=5, pady=5, sticky=tk.W)
    ttk.Label(master=root, text='YTD', width=4, anchor=tk.E).grid(column=2, row=0, padx=5, pady=5)
    ytd_var = tk.StringVar()
    ytd_entry = ttk.Entry(master=root, textvariable=ytd_var, width=10)
    ytd_entry.grid(column=3, row=0, padx=5, pady=5, sticky=tk.W)
    tree_root = ttk.Treeview(master=root, columns=('MTD', 'YTD'))
    tree_root.column('MTD', width=30)
    tree_root.heading('MTD', text='Month to Date', anchor=tk.E)
    tree_root.column('YTD', width=30)
    tree_root.heading('YTD', text='Year to Date', anchor=tk.E)
    iid = tree_root.insert(parent='', index='end', text='Branch One', open=False)
    tree_root.insert(parent=iid, index='end', text='Item 0', values=(100, 1500), tags=('detail',))
    iid = tree_root.insert(parent='', index='end', text='Branch Two', open=True)
    tree_root.insert(parent=iid, index='end', text='Item 1', values=(250, 12000), tags=('detail',))
    tree_root.insert(parent=iid, index=0, text='Item 0')
    tree_root.grid(column=0, row=1, padx=5, pady=5, columnspan=4)
    tree_root.insert(parent=iid, index=1, text='Item 0.5', values=(100, 150))
    tree_root.bind('<<TreeviewSelect>>', tree_select)
    root.mainloop()

Answered By: stroudcuster