【问题标题】:Creating widget with button in .kv file在 .kv 文件中使用按钮创建小部件
【发布时间】:2018-01-07 13:11:33
【问题描述】:

我有一个带有一个按钮的小部件。
SimpleWidget.py

from kivy.properties import ObjectProperty
from kivy.uix.widget import Widget


class SimpleWidget(Widget):
    bt = ObjectProperty()

.kv

<SimpleWidget>:
    bt: button

    Button:
        id: button

如何使用不同的按钮处理程序在 .kv 中创建此小部件?
我试图用这段代码做到这一点

<MainScreen>:
    BoxLayout:
        SimpleWidget:
            bt.on_press: print('1')
        SimpleWidget:
             bt.on_press: print('2')

或者

<MainScreen>:
    BoxLayout:
        SimpleWidget:
            self.button.on_press: print('1')
        SimpleWidget:
             self.button.on_press: print('2')

在这两种情况下都会抛出异常

 ...
      23:    BoxLayout:
      24:        SimpleWidget:
 >>   25:            bt.on_press: print('1')
      26:        SimpleWidget:
      27:            bt.on_press: print('2')
 ...
 Invalid property name

【问题讨论】:

    标签: kivy kivy-language


    【解决方案1】:

    您可以在小部件上定义一个属性。

    SimpleWidget.kv

    <MainScreen>:
        BoxLayout:
            SimpleWidget:
                number: 1
            SimpleWidget:
                number: 2
    
    <SimpleWidget>:
        number: 0
        Button:
            id: button
            on_press: print(root.number)
    

    SimpleWidgetApp.py

    from kivy.uix.widget import Widget
    from kivy.app import App
    from kivy.uix.label import Label
    
    class MainScreen(Widget):
        pass
    
    class SimpleWidget(Widget):
        pass
    
    class SimpleWidgetApp(App):
        def build(self):
            return MainScreen()
    
    if __name__ == '__main__':
        SimpleWidgetApp().run()
    

    【讨论】:

    • 是否有针对任意处理程序的解决方案?我需要类似地在 kv 中编写代码on_press.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2020-02-03
    相关资源
    最近更新 更多