I have the following code to print and insert selected treeview
row in anentry
widget but am having challenges on how to do it.My List profile
doesn't display the content correctly in the treeview
, i want the year to appear under column specify for same as the month.
When i select the row it prints ('end',)
to my terminal and inserts end
in my both entry
widget and not the selected.
from tkinter import *
from tkinter import ttk
profile = [("2012", "JANUARY"),
("2013", "FEBRUARY"),
("2014", "MARCH"),
("2015", "APRIL"),
("2016", "MAY")
]
def content(event):
print(tree.selection()) # this will print the row inserted
for nm in tree.selection():
e1.insert(END, nm)
e2.insert(END, nm)
root = Tk()
tree = ttk.Treeview(root, columns=("columns1","columns2" ), show="headings",
selectmode="browse")
tree.heading("#1", text="YEAR")
tree.heading("#2", text="MONTH")
tree.insert("", 1, END, values=profile)
tree.bind("<<TreeviewSelect>>", content)
tree.pack()
e1 = Entry(root)
e1.pack()
e2 = Entry(root)
e2.pack()
root.mainloop()
First of all, you need to iterate over your profile
list to populate the treeview:
for values in profile:
tree.insert("", END, values=values)
What you were doing:
tree.insert("", 1, END, values=profile)
created one row, with item name 'end' and values the first two tuple of profile
.
I guess that you want to insert the year of the selected row in e1
and the month in e2
. However, tree.selection()
gives you the selected items' name, not the values, but you can get them with year, month = tree.item(nm, 'values')
. So the content
function becomes
def content(event):
print(tree.selection()) # this will print the names of the selected rows
for nm in tree.selection():
year, month = tree.item(nm, 'values')
e1.insert(END, year)
e2.insert(END, month)