4

I have the following code:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout


class GUI(FloatLayout):
    def remove(self):
        self.remove_widget(self.ids.test)


class GUIApp(App):
    def build(self):
        return GUI()


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

And the corresponding kv file:

#:kivy 1.9.1

<GUI>:
    BoxLayout:
        Button:
            id: test
            text: 'Test'
            on_press: root.remove()

The button should be removed when clicked. However, this does not happen. If I remove the BoxLayout in the kv file, the program works as expected, and the button is removed. Why does this happen, and how can I remove a widget declared in a kv file? (I know I can replace the Button's on_press with self.parent.remove_widget(self), but I have code in root.remove() besides removing the widget.)

null
  • 2,060
  • 3
  • 23
  • 42

1 Answers1

4

You're calling remove_widget of GUI object when your button's parent is actually BoxLayout inside it. remove_widget only deletes a direct children, not any descendant.

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder

Builder.load_string('''
<GUI>:
    BoxLayout:
        id: layout
        Button:
            id: test
            text: 'Test'
            on_press: root.remove()
''')


class GUI(FloatLayout):
    def remove(self):
        self.ids.layout.remove_widget(self.ids.test)


class GUIApp(App):
    def build(self):
        return GUI()


if __name__ == '__main__':
    GUIApp().run()
Nykakin
  • 8,657
  • 2
  • 29
  • 42