Python tkinter treeview return iid from selected i

2019-09-14 20:38发布

问题:

In Python tkinter treeview I am trying to make a display that will show certain things based on the iid of the selected treeview item, it takes place on a selection event (mouse click) but I cannot get this working:

def tree_click_event (event):
    iid = treedisplay.identify(event.x,event.y)

treedisplay = ttk.Treeview(root,selectmode='browse')
treedisplay.bind('<<TreeviewSelect>>', tree_click_event)
treedisplay.pack(side='top', fill='both', expand=1)

error:

TypeError: tree_click_event() missing 1 required positional argument: 'y'

this is condensed down to just creating the tree, packing it in a tkinter window, looking for people familiar with this module to know exactly what I've done wrong

Thank you for your example @BryanOakley, it works to get the text of the item. Is there no way to get the below code working though?

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.tree_click_event)

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

        self.root.mainloop()

    def tree_click_event(self, event):
        iid = self.tree.identify(event.x,event.y)
        print (iid)

if __name__ == "__main__":
    app = App()

回答1:

identify requires three arguments and you are only passing it two. The first argument represents a component that you want to identify, and needs to be one of the following: region, item, column, row, or element.

For example:

iid = treedisplay.identify("item", event.x,event.y)

Note: while the above is syntactically correct, it won't quite do what you think it does. In the case of the <<TreeviewSelect>> event, you won't get an x and y coordinate. That is because the event can be fired by both keyboard and mouse events. The identify method should be used for explicit bindings to mouse events, and is mostly only used for low level bindings.

If you want the selected item, use the selection method which will return a list of item ids:

for item in treedisplay.selection():
    item_text = self.tree.item(item,"text")