如何在kivy中动态创建屏幕内的布局?

时间:2017-07-18 10:00:38

标签: python kivy

我写了这个python代码,在屏幕上动态创建一个BoxLayout。

from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class ListScreen(Screen):
    def __init__(self,**kwargs):
        super(ListScreen, self).__init__(**kwargs)          
        layout = BoxLayout(orientation ='vertical')
        top_buttons=BoxLayout()
        layout.add_widget(top_buttons) 
        top_buttons.add_widget(Button(text='Save'))

class ExampleApp(App):
    def build(self):    
        root=ScreenManager()
        root.add_widget(ListScreen(name='list'))
        return root


ExampleApp().run()

它运行时没有任何编译错误,但输出只是一个空白的屏幕。

1 个答案:

答案 0 :(得分:2)

问题是您尚未将layout添加到ListScreen实例:

from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class ListScreen(Screen):
    def __init__(self,**kwargs):
        super(ListScreen, self).__init__(**kwargs)          
        layout = BoxLayout(orientation ='vertical')
        self.add_widget(layout)                         #<<<<<<<<<<<<<<<<<
        top_buttons=BoxLayout()
        layout.add_widget(top_buttons) 
        layout.add_widget(Button(text='Save'))

class ExampleApp(App):
    def build(self):    
        root=ListScreen()
        root.add_widget(ListScreen(name='list'))
        return root


ExampleApp().run()