【发布时间】: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