I noticed a difference between the for loop and the while loop when trying to remove items from a layout. Here is a little code to illustrate:
test.kv
BoxLayout:
orientation: 'vertical'
spacing: 20
BoxLayout:
orientation: 'vertical'
spacing: 20
id : box
Button:
text: 'BUTTON1'
Button:
text: 'BUTTON2'
Button:
text: 'BUTTON3'
Button:
text: 'BUTTON'
size_hint: None, None
size: dp(100), dp(50)
pos_hint: {'center_x': 0.5, 'center_y': 0.1}
on_release: app.del_button()
With a for loop: main.py
from kivy.app import App
class TestApp(App):
def del_button(self):
children = self.root.ids.box.children
for i in children:
self.root.ids.box.remove_widget(i)
if __name__ == '__main__':
TestApp().run()
In this first case, when I press the 'BUTTON', the first and third buttons are removed, but the 'BUTTON2' remains visible.
With a while loop: main.py
from kivy.app import App
class TestApp(App):
def del_button(self):
children = self.root.ids.box.children
i = 0
while i < len(children):
self.root.ids.box.remove_widget(children[i])
if __name__ == '__main__':
TestApp().run()
In this second case, all the buttons are removed directly.
With the for loop, not all elements are removed the first time, while the while loop does the job well. Why this strange behavior?
Thank you in advance for your answers.