复制 Tkinter 树视图 [英] Duplicating a Tkinter treeview

查看:39
本文介绍了复制 Tkinter 树视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在另一个窗口中显示 ttk 树视图.似乎唯一的选择是遍历原始树视图并相应地填充新树视图.

I'm trying to display a ttk treeview in another window. The only option, it seems, is to iterate through the original treeview and populate the new one accordingly.

但是我似乎无法将所有(许多)子文件夹放在正确的位置,从 2d 级别开始,所有内容都被混淆了(即,我正确获取了根文件夹及其子文件夹,之后子文件夹似乎随机插入).

However I can't seem to get all the (many) subfolders in the right place, everything is mixed up as of the 2d level (i.e., I get the root folders and their children right, and after that the subfolders seem to be inserted at random locations).

功能是:

    def getsubchildren(item=''):
        children = []
        for child in original_treeview.get_children(item):
            i = new_treeview.insert(item, 'end', text=original_treeview.item(child) 
                                   ['text'],values=original_treeview.item(child)['values'])
            children.append(i)

        for subchild in children: 
            getsubchildren(subchild)

并使用 getsubchildren(item='') 调用函数,从第一级开始迭代.一定是我做错了什么,但我无法确定问题所在,而我修改函数的尝试只得到了较差的结果.有什么想法吗?

And calling the function with getsubchildren(item=''), to start iterating from the first level. There must be something I'm doing wrong, but I can't identify the issue and my attempts at modifying the function have only given a poorer result. Any idea ?

谢谢,

推荐答案

在不知道项目深度的情况下,您需要检查项目是否有子项.如果是这样,您需要该函数在循环中调用自身.这是一个工作示例:

Without known the depth of the item you need to check if the item has children. If so you need the function to call itself in a loop. Here is a working exampel:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

maintree = ttk.Treeview(root)
maintree.pack()

first = maintree.insert("","end",text='first')
second= maintree.insert(first,"end",text='second')
third= maintree.insert(second,"end",text='third')
fourth= maintree.insert(third,"end",text='fourth')

st = maintree.insert("","end",text='1st')
nd= maintree.insert(st,"end",text='2nd')
rd= maintree.insert(nd,"end",text='3rd')
th= maintree.insert(rd,"end",text='4th')

top = tk.Toplevel(root)
subtree = ttk.Treeview(top)
subtree.pack()

def copy_item_tree(item,child):
    for child in maintree.get_children(child):
        item = subtree.insert(item,"end",
                              text=maintree.item(child)['text'])
        if maintree.get_children(child):
            copy_item_tree(item,child)
def copy_tree():
    for child in maintree.get_children():
        item = subtree.insert("","end",text=maintree.item(child)['text'])
        copy_item_tree(item,child)

button = tk.Button(root,text='Copy Tree', command=copy_tree)
button.pack(fill='x')
root.mainloop()

这篇关于复制 Tkinter 树视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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