jdanaher jdanaher - 7 months ago 100
Python Question

Layouts within Layouts in Kivy with Python

I want to make a layout within a layout using the

Kivy
library in Python instead of using the Kivy language builder as shown below:

Builder.load_string("""
<ListScreen>:
BoxLayout:
orientation: 'vertical'
BoxLayout:
size_hint_y: .1
Button:
text: 'Save'
Button:
text: 'Load'
Button:
text: 'New'
Button:
text: 'New'
on_press:
root.manager.transition.direction = 'down'
root.manager.current = 'search'
""")


I am having difficulty figuring out how to access the second layout to add widgets to it. Sample code below:

class ListScreen(Screen):
layout = BoxLayout(orientation ='vertical')
layout.add_widget(top_buttons=BoxLayout())
top_buttons.add_widget(save=Button(text='Save')
# ^ problem here, it won't recognize top_buttons


As you can see, I tried to access top_buttons outside of the layout, but I can't figure out how to reach it, so I cannot add my widgets to it. How should I access it to add widgets?

Answer
class ListScreen(Screen):

    layout = BoxLayout(orientation ='vertical')
    layout.add_widget(top_buttons=BoxLayout()) # <--------
    top_buttons.add_widget(save=Button(text='Save')

Exactly because of that line you can't use the variable top_buttons, because you used that as a keyword, not a variable. It should look like this:

class ListScreen(Screen):

    layout = BoxLayout(orientation ='vertical')
    top_buttons=BoxLayout()
    layout.add_widget(top_buttons) # <--------
    top_buttons.add_widget(save=Button(text='Save')