Lyman Zerga
Lyman Zerga

Reputation: 1515

Switch BoxLayout to vertical in Kivy and get widgets by id in Python code

I am creating an Accordion widget on hitting enter on a text-input.

Following is the python code:

class LabelNavigatorWidget(BoxLayout):
    def create_accordion_widget(self):
        self.cleanup_root()
        root = Accordion(id='accordion_widget', orientation='vertical')
        for x in range(2):
            item = AccordionItem(title='Title %d' % x)
            item.add_widget(Label(text='Very big content\n' * 10))
            root.add_widget(item)
        self.add_widget(root)
        return root

    def cleanup_root(self):
        # Remove previous widget
        for child in self.children:
            if child.id == 'accordion_widget':
                self.remove_widget(child)

class LabelNavigatorApp(App):
    def build(self):
        return LabelNavigatorWidget()

if __name__ == "__main__":
    LabelNavigatorApp().run()

Below is the kv code:

<LabelNavigatorWidget>:
    BoxLayout:
        orientation: 'vertical'
        TextInput:
            id: label_input
            font_size: 30
            pos: 0, 0
            size_hint_y: None
            height: 50
            multiline: False
            text: ''
            on_text_validate: root.create_accordion_widget(); self.text = ''

This is how it looks:

Incorrect BoxLayout

  1. So, the default BoxLayout is horizontal, how can I set it to vertical ?
  2. The initial location of the text-input is at the bottom of the BoxLayout, how can I make it sit at the top ?
  3. Whenever, I hit enter, it will create a new accordion widget - that is why I am removing the previous widget before I create a new one. However, is there a better way to get the child widget (say by id?) and then remove it instead of iterating through all children ?

Upvotes: 1

Views: 1402

Answers (1)

inclement
inclement

Reputation: 29460

So, the default BoxLayout is horizontal, how can I set it to vertical ?

The same way as with the other BoxLayout, just set orientation: 'vertical'.

<LabelNavigatorWidget>:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'vertical'

The initial location of the text-input is at the bottom of the BoxLayout, how can I make it sit at the top ?

Add an empty widget to fill the remaining space.

BoxLayout:
    orientation: 'vertical'
    TextInput:
        size_hint_y: None
        height: 50
        # ... and the rest
    Widget:

Whenever, I hit enter, it will create a new accordion widget - that is why I am removing the previous widget before I create a new one. However, is there a better way to get the child widget (say by id?) and then remove it instead of iterating through all children ?

You could store a reference to it as an attribute, e.g. self.accordion_widget = AccordionWidget(...) then later self.remove_widget(self.accordion_widget).

Upvotes: 3

Related Questions