Tell me, is it possible to somehow make a function call when you click on a particular element of the treeview? Here is the tree itself:

root = Tk() frame_tree=Frame(root) treeview = ttk.Treeview(frame_tree) treeview.insert('','0','material', text='Материал') treeview.insert('material','0','coil', text='Катушка') treeview.insert('coil','0','shell', text = 'Оболочка') treeview.insert('coil','1','conductor', text = 'Проводник') treeview.insert('conductor','0','cable', text = 'Кабель') treeview.insert('material','1','size_pipeline', text='Типоразмер трубопровода') treeview.insert('size_pipeline','0','aluminum_alloy', text='Алюминиевые сплавы') treeview.item('material', open=True) frame_tree.pack(padx=10, pady=10, side = 'left') treeview.pack() root.mainloop() 

For example, I chose "Coil", when you click on this element, the function should be executed, when you click on another element, another function should be executed.

  • Thanks, it helped) it was possible not to specify in principle, I understood everything at once) It was not possible to answer, unfortunately. - Nikc174 pm

1 answer 1

To get started, just try to bind to the treeview's <<TreeviewSelect>> virtual event and get information about the selected elements:

 ... def on_select(event): print(event) print(treeview.selection()) treeview.bind('<<TreeviewSelect>>', on_select) root.mainloop() 

Screenshot 1

For the first time, I simply chose the coil, the second time - with the shift key held down, I also chose "Pipe Size" - as a result, all the elements between the coil and the size were also selected.

We assume that we only need the first selected item (to prevent the selection of several items, you can specify the browse mode when creating the Treeview:
treeview = ttk.Treeview(frame_tree, selectmode='browse') )

Then there are several ways. You can simply check which element is selected in if, depending on this, call some function, or you can, for example, create a dictionary in which functions are associated with the necessary elements (to shorten the code through lambdas, but for a more extensive code it makes sense to create functions via def ):

 funcs_for_items = { 'coil': lambda: print('Function 1'), 'size_pipeline': lambda: print('Function 2') } def on_select(event): item = treeview.selection()[0] print(item) # Выбираем функцию из словаря, если элемента в словаре нет - выполняется действие по-умолчанию func = funcs_for_items.get(item, lambda: print('Default action')) func() treeview.bind('<<TreeviewSelect>>', on_select) root.mainloop() 

Screenshot 2