Hello.
How to clear all the nodes in TreeView widget? I made up one way but there're a question that confuses me.
tree_view_sandbox.py
from kivy.app import App
from kivy.uix.treeview import TreeViewLabel
from kivy.uix.floatlayout import FloatLayout
class main_window(FloatLayout):
def tree_populate(self, tv):
tv.add_node(TreeViewLabel(text='My first item'))
tv.add_node(TreeViewLabel(text='My second item'))
tv.add_node(TreeViewLabel(text='My third item'))
tv.add_node(TreeViewLabel(text='My fourth item'))
tv.add_node(TreeViewLabel(text='My fifth item'))
tv.add_node(TreeViewLabel(text='My sixth item'))
tv.add_node(TreeViewLabel(text='My seventh item'))
tv.add_node(TreeViewLabel(text='My eighth item'))
def tree_clear(self, tv):
while tv.root.nodes: #for some reason, kivy clears only part of nodes with just FOR loop
for node in tv.root.nodes:
tv.remove_node(node)
class tree_view_sandboxApp(App):
title = "TreeView Sandbox"
def build(self):
return main_window()
if __name__ == '__main__':
tree_view_sandboxApp().run()
tree_view_sandbox.kv
<main_window>:
BoxLayout:
orientation: 'vertical'
size_hint: None, None
width: 500
height: 400
top: root.top
BoxLayout:
orientation: 'horizontal'
size_hint: 1, None
height: 40
Button:
text: 'Populate'
size_hint: 0.5, 1
on_press: root.tree_populate(tv)
Button:
text: 'Clear'
size_hint: 0.5, 1
on_press: root.tree_clear(tv)
TreeView:
id: tv
root_options: dict(text='Sandbox tree root')
This code works. When I press "Populate" button, Tree appears. Then, I press "Clear" button, all the nodes disappear. BUT! I expect that code should be:
def tree_clear(self, tv):
for node in tv.root.nodes:
tv.remove_node(node)
In this case, when I press "Clear" button, nodes disappear partially. First pressing - "Second", "Fourth", "Sixth" and "Eight" nodes are still alive. Second pressing - "Fourth" and "Eight" here. Third pressing - "Eight" remains. Fourth pressing - there're no nodes.
P.S. I get exactly the same result If I use the builtin method iterate_all_nodes():
def tree_clear(self, tv):
for node in tv.iterate_all_nodes():
tv.remove_node(node)
def tree_clear(self, tv):
while tv.root.nodes:
for node in tv.iterate_all_nodes():
tv.remove_node(node)
Why does it works in that manner?