Skip to content
Advertisement

How to get the value of a selected treeview item?

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

Advertisement

Answer

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()
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement