将树视图中的选定行打印并插入到 tkinter 条目小部件中 [英] Printing and inserting selected row in treeview into tkinter entry widget

查看:26
本文介绍了将树视图中的选定行打印并插入到 tkinter 条目小部件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以在 entry 小部件中打印和插入选定的 treeview 行,但我在如何做方面遇到了挑战.我的 List profile 没有在 treeview 中正确显示内容,我希望年份出现在与月份相同的列指定下.

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.

当我选择行时,它会将 ('end',) 打印到我的终端并在我的两个 entry 小部件中插入 end 而不是被选中.

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()

推荐答案

首先,您需要遍历您的 profile 列表以填充树视图:

First of all, you need to iterate over your profile list to populate the treeview:

for values in profile:
    tree.insert("", END, values=values)

你在做什么:

tree.insert("", 1, END, values=profile)

创建了一行,项目名称为end",并为 profile 的前两个元组赋值.

created one row, with item name 'end' and values the first two tuple of profile.

我猜您想在 e1 中插入所选行的年份,在 e2 中插入月份.但是,tree.selection() 为您提供所选项目的名称,而不是值,但您可以使用 year, month = tree.item(nm, 'values').所以 content 函数变成了

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)

这篇关于将树视图中的选定行打印并插入到 tkinter 条目小部件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆