简体   繁体   中英

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM