【问题标题】:How to create button in kivy using class inheritance from Screen如何使用来自 Screen 的类继承在 kivy 中创建按钮
【发布时间】:2020-11-10 08:53:08
【问题描述】:

我想使用 python 代码动态创建 Kivy 按钮。到目前为止,这很有效,但是现在我遇到了需要在继承自 Kivy Screen 的类中创建按钮的情况。 不幸的是,这不会在我的屏幕上添加一个按钮。

请看我下面的示例代码。 L. 40 会出现问题,如果我在 ExampleScreen 的 init 中调用函数 add_button(),则会添加按钮。但是,如果我在继承自此 Screen 的类中调用此函数,则不会添加按钮(L. 40)。

我希望有人可以帮助我或解释为什么这不起作用。感谢您的帮助。

编辑:按钮被添加为布局的子项(print(self.box_layout_button.children) 产生所有三个按钮对象),但它只是不可见......

example.py

class ExampleScreen(Screen):

    label_text = NumericProperty(501)

    def __init__(self, **kwargs):
        super(ExampleScreen, self).__init__(**kwargs)
        # This works
        def decrement(instance):
            self.label_text -= 1
        self.button = Button(text="Test Button 1")
        self.box_layout_button.add_widget(self.button)
        self.button.bind(on_press=decrement)

        # This works
        self.add_button()

    def add_button(self, label='Test Button 2'):
        def decrement(instance):
            self.label_text -= 1

        self.button = Button(text=label)
        self.box_layout_button.add_widget(self.button)
        self.button.bind(on_press=decrement)



class X01_Game(ExampleScreen):
    def __init__(self, *args, **kwargs):
        super(X01_Game, self).__init__(*args, **kwargs)

    def init(self):
        # This does not add a button
        self.add_button(label='Test Button 3')


class ExampleApp(App):
    def build(self):
        # Create the screen manager
        sm = ScreenManager(transition=SwapTransition())
        sm.add_widget(ExampleScreen(name='example_page'))
        sm.current = 'example_page'

        game = X01_Game()
        game.init()

        return sm


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

example.kv

#:kivy 2.0.0

<ExampleScreen>:
    box_layout_button: box_layout_button
    name: 'example_page'
    BoxLayout:
        orientation: 'vertical'
        size_hint: 1.0, 0.4
        size: root.size
        id: box_layout_button

        Label:
            font_size: 20
            bold: True
            text: str(root.label_text)

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    问题是您正在创建X01_Game 的实例,但没有将其添加到ScreenManager。尝试像这样修改您的 ExampleApp 类:

    class ExampleApp(App):
        def build(self):
            # Create the screen manager
            sm = ScreenManager(transition=SwapTransition())
            sm.add_widget(ExampleScreen(name='example_page'))
            game = X01_Game(name='game')
            game.init()
            sm.add_widget(game)
            sm.current = 'game'
    
            return sm
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多