如何使用Kivy的remove_小部件删除所有子元素

2024-04-26 07:05:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了以下代码:

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

rootBoxLayout中有五个boxlayout

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

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

enter image description here

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


Tags: textfromimportselfsizeinitdefbutton
1条回答
网友
1楼 · 发布于 2024-04-26 07:05:37

嗯,这确实是一个常见的疏忽。
Removing items of an iterable while iterating over it

修复它的方法是如下更改removeAllBoxLayout方法:

    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)

相关问题 更多 >