1

I wrote the following code:

#-*- coding: utf-8 -*-

from kivy.lang import Builder
Builder.load_string("""
<TestWidget>:
    BoxLayout:
        id: rootBoxLayout
        orientation: 'vertical'
        size: root.size

        BoxLayout:
            Button:
                text: "Button1"

        BoxLayout:
            Button:
                text: "Button2"

        BoxLayout:
            Button:
                text: "Button3"

        BoxLayout:
            Button:
                text: "Button4"

        BoxLayout:
            Button:
                text: "Button5"

        Button:
            text: "removeAllBoxLayout"
            font_size: 48
            on_press: root.removeAllBoxLayout()
""")

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout

class TestWidget(Widget):
    def __init__(self, **kwargs):
        super(TestWidget, self).__init__(**kwargs)

    def removeAllBoxLayout(self):
        for row1 in self.ids.rootBoxLayout.children:
            if isinstance(row1, BoxLayout):
                self.ids.rootBoxLayout.remove_widget(row1)

class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)

    def build(self):
        return TestWidget()

if __name__ == '__main__':
    TestApp().run()

There are five BoxLayouts in the rootBoxLayout.

I want to remove all 5 BoxLayouts when I press the "removeAllBoxLayout" button.

But when I press the "removeAllBoxLayout" button, it actually only removes 3 buttons.

enter image description here

How do I remove all the BoxLayouts that are children of the rootBoxLayout?

taichi
  • 631
  • 1
  • 7
  • 26

1 Answers1

3

Well, its a really common oversight.
Removing items of an iterable while iterating over it.

The way to fix it, is to change your removeAllBoxLayout method like this:

    def removeAllBoxLayout(self):
        rows = [i for i in self.ids.rootBoxLayout.children]
        for row1 in rows:
            if isinstance(row1, BoxLayout):
                self.ids.rootBoxLayout.remove_widget(row1)
noEmbryo
  • 2,176
  • 2
  • 10
  • 15