Agenobarb
Agenobarb

Reputation: 153

Python KIvy: Why layout not changed?

From the below code I expect layout to be changed from BoxLayout to GridLayout in show_buttons() method but it is not happening and I am still seeing BoxLayout. I would appreciate an explanation, thank you.

class MainScreen(BoxLayout):

    def show_buttons(self, button):
        self.clear_widgets()
        self.layout = GridLayout(cols=2)
        if button.text == 'Button 1':
            for x in range (100, 110):
              t = ('Button %s' % x)
              self.add_widget(Button(text=t))

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.orientation='vertical'
        self.add_widget(Label(text='Select Button', size_hint = (1, 0.2)))
        self.button1=Button(text="Button 1")
        self.button1.bind(on_press=self.show_buttons)
        self.add_widget(self.button1)
        self.button2=Button(text="Button 2")
        self.button2.bind(on_press=self.show_buttons)
        self.add_widget(self.button2)             

class MyApp(App):
    def build(self): 
        return MainScreen() 

if __name__ == '__main__':
    MyApp().run()

Upvotes: 0

Views: 51

Answers (1)

Yoav Glazner
Yoav Glazner

Reputation: 8041

You forgot to add the GridLayout to the parent...

def show_buttons(self, button):
    self.clear_widgets()
    self.layout = GridLayout(cols=2, size_hint=(1.0, 1.0))
    if button.text == 'Button 1':
        for x in range (100, 110):
          t = ('Button %s' % x)
          self.add_widget(Button(text=t))
    self.add_widget(self.layout) # <-----------------

That said, You might want to rethink about clearing the widgets and just move to a diffent screen using a ScreenManager

Upvotes: 1

Related Questions