问题
I made a treeview, and I want to add values in first and second column and then the program needs to calculate the values that will put in third column when you press the ENTER button (I used events and binds). I do not know how to put values in the specific column in treeview , I always get this error:
TypeError: 'float' object is not subscriptable
I know how to insert values in every column at once, but I do not know how to insert only one value to a specific column, without changing the values in other columns. This is the function that I wrote:
def PlannedCosPerSize(event):
try:
for child in tree.get_children():
Size=round(float(tree.item(child,"values")[1]),2)
PlannedCost=round(float(tree.item(child,"values")[2]),2)
PlanCostPerSize=float(round(PlannedCost/Size,2))
tree.insert("","end", values=(PlanCostPerSize)[4])
print(PlanCostPerSize)
except IndexError:
Error=messagebox.showinfo("error","You have error")
pass
tree.bind('<Return>', PlannedCosPerSize) # validate with Enter
回答1:
The insert
method is creating a new item in the Treeview
but what you want to do is editing an existing item, so this is not the method to use.
One possibility is to use the set
method of the Treeview
to either get or set the value in a specific column:
treeview.set(item, '#1')
will give you the value in the first column.treeview.set(item, '#3', new_value)
will change the value of the third column intonew_value
.
You can also use the column's name (the one given in columns=
when creating the Treeview
) instead of '#<column number>'
.
Another possibility is to use the item
method:
old_values = treeview.item(item, 'values')
will give you the values of the item.treeview.item(item, values=(old_values[0], old_values[1], new_value))
will change the last value of the item.
Documentation on the Treeview widget: https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/ttk-Treeview.html
来源:https://stackoverflow.com/questions/50024404/adding-values-to-specific-column-in-treeview-tkinter