如何避免 pysimpleGUI 树(Tk 树?)中的重复父项

How do I avoid duplicate parents in pysimpleGUI tree (Tk tree?)

给定点符号字符串列表,我需要将它们排列在 pySiplmpleGUI 树中,但我不知道如何正确跟踪父级。例如,如果我有 3 个字符串:

['a.1',
 'a.b.1',
 'a.b.2']
 

我预计:

a
 |_
   1
 |_
   b
   |_
   | 1
   |_
     2

我得到的是

a
 |_
   1
a
 |_
   b
   |_
     1
a
 |_
   b
   |_
     2

我原以为它会使用“a”作为所有内容的父项,但每个条目都在其自己的 a 级别中。但是所有的“a”都有相同的键,并被用作所有其他条目的父项。我的调试器显示它们都有相同的父“a”,那么为什么它们不列在单个“a”下?

下面是列表中的一些要测试的案例的代码:

    #!/usr/bin/env python

import PySimpleGUI as sg

treedata = sg.TreeData()

sigs = ['a.1',
 'a.2',
 'a.3',
 'a.b.1',
 'a.b.2',
 'a.b.c.1',
 'a.b.c.4',
 'a.b.d.1',
 'a.b.d.5',
 'a.b.d.6']

for i, val in enumerate(sigs) :     
    separated = val.split(".") # creates list of dot-pathed names
    fullname = '' 
    for f in separated:
         parent=fullname
         if fullname =='':
             fullname=f
         else:
             fullname = fullname+'.'+f #rebuild the name step by step to use as the key
         
         treedata.insert(parent, fullname, f, values=[] );
    
 
layout = [[ sg.Text('File and folder browser Test') ],
          [ sg.Tree(data=treedata, headings=['col1', 'col2', 'col3'], auto_size_columns=True, num_rows=20, col0_width=30, key='_TREE_', show_expanded=False,),
            ],
          [ sg.Button('Ok'), sg.Button('Cancel')]]

window = sg.Window('Tree Element Test').Layout(layout)


while True:     # Event Loop
    event, values = window.Read()
    if event in (None, 'Cancel'):
        break
    print(event, values)

我明白了,但只需要从 pysimplegui 的 github 获得一点洞察力。使用工作代码的解决方案:https://github.com/PySimpleGUI/PySimpleGUI/issues/1170#issuecomment-671657177