简体   繁体   English

将树视图中的选定行打印并插入到 tkinter 条目小部件中

[英]Printing and inserting selected row in treeview into tkinter entry widget

I have the following code to print and insert selected treeview row in an entry 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.我有以下代码可以在entry小部件中打印和插入选定的treeview行,但在如何执行方面遇到了挑战。我的List profile没有在treeview正确显示内容,我希望年份出现在列指定下和月份一样。

When i select the row it prints ('end',) to my terminal and inserts end in my both entry widget and not the selected.当我选择该行时,它会将('end',)打印到我的终端并在我的两个entry小部件中插入end而不是选定的。

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:首先,您需要遍历您的profile列表以填充树视图:

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 .创建了一行,项目名称为 'end' 并为profile的前两个元组赋值。

I guess that you want to insert the year of the selected row in e1 and the month in e2 .我猜您想在e1插入所选行的年份,在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') .但是, tree.selection()为您提供所选项目的名称,而不是值,但您可以使用year, month = tree.item(nm, 'values')获取它们。 So the content function becomes所以content函数变成

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM