5

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?

blakebullwinkel
  • 305
  • 1
  • 5
  • 15

2 Answers2

4

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)
Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36
-1

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.

Edvardas Dlugauskas
  • 1,469
  • 1
  • 12
  • 14
  • @YoavGlazner yes, but neither are any actual children checks if we judge by the example OP gave us. Sorry, I'm just used to using kivy properties - they're so undervalued in my opinion. I wonder if they have much overhead if used instead of regular Python attributes, do you happen to know? – Edvardas Dlugauskas Jun 05 '17 at 18:12
  • for this use-case they are a bit heavier since they use the **descriptor protocol** - https://docs.python.org/3.6/howto/descriptor.html - they are implemented in cython, though. – Yoav Glazner Jun 05 '17 at 20:36