2017-07-26 47 views
0

從下面的代碼中,我期望在show_buttons()方法中將佈局從BoxLayout更改爲GridLayout,但它沒有發生,我仍然看到BoxLayout。我會很感激一個解釋,謝謝。Python KIvy:爲什麼佈局沒有改變?

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

回答

1

你忘了GridLayout的添加到父...

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

這就是說,你可能要重新考慮有關清除小部件,只是使用ScreenManager移動到屏幕diffent