Python 如何使用Kivy'删除所有子元素;s删除_小部件

Python 如何使用Kivy'删除所有子元素;s删除_小部件,python,kivy,Python,Kivy,我编写了以下代码: #-*- coding: utf-8 -*- from kivy.lang import Builder Builder.load_string(""" <TestWidget>: BoxLayout: id: rootBoxLayout orientation: 'vertical' size: root.size BoxLayout: Button:

我编写了以下代码:

#-*- 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()
#-*-编码:utf-8-*-
从kivy.lang导入生成器
生成器。加载\u字符串(“”)
:
盒子布局:
id:rootBoxLayout
方向:“垂直”
大小:root.size
盒子布局:
按钮:
文本:“按钮1”
盒子布局:
按钮:
文本:“按钮2”
盒子布局:
按钮:
文本:“按钮3”
盒子布局:
按钮:
文本:“按钮4”
盒子布局:
按钮:
文本:“按钮5”
按钮:
文本:“removeAllBoxLayout”
字号:48
按:root.removeAllBoxLayout()
""")
从kivy.app导入应用程序
从kivy.uix.widget导入widget
从kivy.uix.boxlayout导入boxlayout
类TestWidget(小部件):
定义初始(自我,**kwargs):
超级(TestWidget,self)。\uuuuuu初始化(**kwargs)
def removeAllBoxLayout(自身):
对于self.ids.rootBoxLayout.children中的第1行:
如果isinstance(第1行,BoxLayout):
self.ids.rootBoxLayout.remove_小部件(第1行)
类TestApp(应用程序):
定义初始(自我,**kwargs):
超级(测试,自我)。\uuuuu初始(**kwargs)
def生成(自):
返回TestWidget()
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
TestApp().run()
rootBoxLayout中有五个boxlayout

当我按下“removeAllBoxLayout”按钮时,我想删除所有5个BoxLayout

但当我按下“removeAllBoxLayout”按钮时,它实际上只删除了3个按钮


如何删除作为rootBoxLayout子项的所有boxlayout?

嗯,这是一个非常常见的疏忽。

解决方法是更改
removeAllBoxLayout
方法,如下所示:

def removeAllBoxLayout(自):
rows=[self.ids.rootBoxLayout.children中的i代表i]
对于行中的第1行:
如果isinstance(第1行,BoxLayout):
self.ids.rootBoxLayout.remove_小部件(第1行)

嗯,这是一个很常见的疏忽。

解决方法是更改
removeAllBoxLayout
方法,如下所示:

def removeAllBoxLayout(自):
rows=[self.ids.rootBoxLayout.children中的i代表i]
对于行中的第1行:
如果isinstance(第1行,BoxLayout):
self.ids.rootBoxLayout.remove_小部件(第1行)