Python Kivy:如何检查是否存在子部件

Python Kivy:如何检查是否存在子部件,python,python-3.x,kivy,kivy-language,Python,Python 3.x,Kivy,Kivy Language,在我的.py文件中,我有一个屏幕,看起来像: class ExampleScreen(Screen): def create_layout(self): box = BoxLayout(orientation='vertical') # other layout stuff in here self.add_widget(box) def create_layout(self): if (box layout child has

在我的.py文件中,我有一个屏幕,看起来像:

class ExampleScreen(Screen):
    def create_layout(self):
        box = BoxLayout(orientation='vertical')
        # other layout stuff in here
        self.add_widget(box)
def create_layout(self):
    if (box layout child has already been added):
        self.remove_widget(box layout child)
    box = BoxLayout(orientation='vertical')
    # other layout stuff in here
    self.add_widget(box)
在我的.kv文件中,我有一个按钮,按下该按钮时,调用该函数并在
上显示该布局。但是,我希望能够按下这个按钮,首先检查这个布局是否已经存在,如果已经存在,在添加新布局之前删除它。我预计将
create\u layout()
修改为类似以下内容:

class ExampleScreen(Screen):
    def create_layout(self):
        box = BoxLayout(orientation='vertical')
        # other layout stuff in here
        self.add_widget(box)
def create_layout(self):
    if (box layout child has already been added):
        self.remove_widget(box layout child)
    box = BoxLayout(orientation='vertical')
    # other layout stuff in here
    self.add_widget(box)

有人知道怎么做吗?以某种方式使用
id

您可以使用id或其他子检查来完成,但最简单、最直接的方法是在类中设置一个布尔标志,当您添加小部件时,该标志将变为
True
,当您删除它时,该标志将变为
False
。否则,您还可以创建一个kivy
box\u obj=ObjectProperty(None)
并执行
self.box\u obj=box
,然后检查
self.box\u obj
是否为None。

每个小部件都有一个子属性,因此您可能需要使用它

for c in list(self.children):
    if isinstance(c, BoxLayout): self.remove(c)
您还可以将其分配给小部件:(如Edvardas Dlugauskas anwser中所述)


@YoavGlazner是的,但如果我们根据OP给我们的例子来判断,也没有任何实际的儿童检查。对不起,我只是习惯于使用kivy的房产——在我看来,它们被低估了。我想知道,如果用它们代替常规的Python属性,它们是否会有很大的开销,你知道吗?对于这个用例,它们会有点重,因为它们使用描述符协议——不过它们是用cython实现的。