title: PySimpleGui Tree Add Elements with an Event to Reduce Startup Time
body: <p>I am trying to add a GUI to a command line program I made. I needed a file tree to select files for the program. I found one using PySimpleGUI but it takes a while for it to start since it has to recursively go through files.</p>
  <p>I was able to fix this by limiting the recursion depth and using <code>update(values=treedata)</code> after inserting TreeData. This though resets the tree (closes all open expanded folders) and is a terrible user experience.</p>
  <p>The <code>update</code> function also lets you modify nodes with <code>key</code> and <code>value</code> but can you add nodes and define their parent? I can't seem to find if/how you do this.</p>
  <p>Is there a way to add child nodes or a better/faster way to add many files to the treedata structure?</p>
  <p>Thanks in advance.</p>
  <p><a href="https://i.stack.imgur.com/liCAT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/liCAT.png" alt="Gui Picture" /></a></p>
  <p>Loop</p>
  <pre><code>while True:  # Event Loop
      event, values = window.read()
      tree.update()
      try:
          v = values[tree_key][0]  # clicked file/folder
          print(v)
      except TypeError:
          pass
      if event == tree_key
          add_files_in_folder(v, v, 2, False)
          tree.update(values=treedata) 
  
      if event in (sg.WIN_CLOSED, 'Cancel', True):
          break
      print(event, values)
  </code></pre>
  <p>Recursive</p>
  <pre><code>def add_files_in_folder(parent, dirname, recursion_limit, tree_created):
      if recursion_limit != 0:
          try:
              files = os.listdir(dirname)
          except PermissionError:
              return
          if not opened_folders.__contains__(dirname):
              opened_folders.append(dirname)
              for f in files:
                  fullname = os.path.join(dirname, f)
                  if os.path.isdir(fullname):  # if it's a folder, add folder and recurse
                      treedata.insert(parent, fullname, f, values=[], icon=folder_icon)
                      add_files_in_folder(fullname, fullname, recursion_limit - 1, tree_created)
                  else:
                      treedata.insert(parent, fullname, f, values=[os.stat(fullname).st_size], icon=file_icon)
  </code></pre>