Reputation: 335
In my .py file I have a screen that looks something like:
class ExampleScreen(Screen):
def create_layout(self):
box = BoxLayout(orientation='vertical')
# other layout stuff in here
self.add_widget(box)
In my .kv file, I have a button which, when pressed, calls this function and displays this layout on <ExampleScreen>
. However, I would like to be able to press this button and first check if this layout already exists, and if so, remove it before adding a new one. I anticipate modifying create_layout()
to something like:
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)
Does anyone know how to do this? Using id
somehow?
Upvotes: 6
Views: 5060
Reputation: 8066
Each widget has a children property so you may want to use it.
for c in list(self.children):
if isinstance(c, BoxLayout): self.remove(c)
You can also assign it to the widget: (as mentioned in Edvardas Dlugauskas anwser)
def __init__(self, **kw):
self.box = None
...
def create_layout(self):
if self.box: self.remove(self.box)
self.box = BoxLayout(orientation='vertical')
self.add_widget(box)
Upvotes: 5
Reputation: 1489
Well, you can do it with an id or some other child checks, but the easiest and most straight-forward way would be to have a boolean flag in your class that would change to True
when you added the widget and False
when you removed it. Otherwise, you can also create a kivy box_obj = ObjectProperty(None)
and do self.box_obj = box
and then check if the self.box_obj
is not None.
Upvotes: -1