在ScreenManager Kivy中向屏幕动态添加按钮时出错

时间:2016-10-14 10:08:57

标签: python kivy

我正在尝试将按钮动态添加到屏幕上。运行应用程序时出现以下错误。请帮我解决这个问题。

  

回溯(最近一次调用最后一次):文件“main.py”,第174行,在           screenManager.add_widget(HomeScreen(name ='homeScreen'))文件“main.py”,第162行, init        self.add_widget(btn)文件“/Applications/Kivy.app/Contents/Resources/kivy/kivy/uix/floatlayout.py”,   第111行,在add_widget中        pos = self._trigger_layout,AttributeError:'HomeScreen'对象没有属性'_trigger_layout'

这是我的main.py

class HomeScreen(Screen):

    def __init__(self, **kwargs):
        for i in range(80):
            btn = Button(text=str(i), size=(90, 90), size_hint=(None, None))
            self.add_widget(btn)


# Screen Manager
screenManager = ScreenManager( transition = FadeTransition() )

# Add all screens to screen manager
#screenManager.add_widget( UsernameScreen( name = 'usernameScreen' ) )
#screenManager.add_widget( PasswordScreen( name = 'passwordScreen' ) )
#screenManager.add_widget( LevelTwoScreen( name = 'levelTwoScreen' ) )
#screenManager.add_widget( LevelTwoScreen( name = 'levelThreeScreen' ) )

screenManager.add_widget( HomeScreen( name = 'homeScreen' ) )

class ThreeLevelAuthApp(App):
    def build(self):
        return screenManager

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

kivy文件

<HomeScreen>:
    ScrollView:
        size_hint: None, None
        size: 400, 400
        pos_hint: { 'center_x': 0.5,'center_y': 0.5 }   
        do_scroll_x: False

    GridLayout:
        cols: 6
        padding: 20
        spacing: 20
        size_hint: None, None
        width: 400

1 个答案:

答案 0 :(得分:0)

让我们从__init__开始:

class HomeScreen(Screen):

    def __init__(self, **kwargs):
        for i in range(80):
            btn = Button(text=str(i), size=(90, 90), size_hint=(None, None))
            self.add_widget(btn)

虽然这看起来很好并且在你创建一个实例时被调用,但是缺少一个基本的东西 - super()。您需要super()首先初始化Screen,以便它具有使其成为具有真实行为的类的所有必需变量和方法,从而使您能够实际继承行为。

请注意,Screen本身是RelativeLayout,如果您不使用适合您的布局,则需要处理其他内容,例如定位和/或调整大小。< / p>

import random
class HomeScreen(Screen):

    def __init__(self, **kwargs):
        super(HomeScreen, self).__init__(**kwargs)
        for i in range(80):
            btn = Button(text=str(i), size=(90, 90),
                         size_hint=(None, None),
                         pos=[random.randint(0,500), random.randint(0,500)])
            self.add_widget(btn)