Kivy - Removing widget by id

点点圈 提交于 2021-02-07 09:12:36

问题


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.)


回答1:


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()


来源:https://stackoverflow.com/questions/42173477/kivy-removing-widget-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!