How do I get data from a Treeview?
How do I open a window when I click on the Treeview Tkinter line? That is, the user clicks on the line with the data he needs and a new window opens, where the same data as in this line + everything else from the database. I know how to output data from the database to a separate window, but I don't understand how to take data from the selected row in the Treeview. Please tell me
1 answers
Let's say we need to perform some action when selecting a row in the tree, and we need to access the data in the selected row. To react to the row selection, you need to bind to the <<TreeviewSelect>>
event of the tree (in principle, you can use another event, for example, double-click with the left mouse button - <Double-Button-1>
). Then, using the tree method selection
, you need to get a list of the IDs of the selected elements. Then you can get the values in the string by id.
def on_select(event):
# вывод текстовых id всех выбранных строк
# (их может быть несколько, если при создании дерева не было указано selectmode='browse')
print(treeview.selection())
# Если привязывались не к событию <<TreeviewSelect>>,
# то тут нужно проверить, что вообще что-то выбрано:
if not treeview.selection():
return
# Получаем id первого выделенного элемента
selected_item = treeview.selection()[0]
# Получаем значения в выделенной строке
values = treeview.item(selected_item, option="values")
print(values)
treeview.bind('<<TreeviewSelect>>', on_select)