首页 > 解决方案 > Kivy 开关回调

问题描述

我对基维很陌生。请帮助我使开关小部件正常工作。这是我当前的代码:

    from kivy.app import App
    from kivy.base import runTouchApp
    from kivy.lang import Builder
    runTouchApp(Builder.load_string('''

    StackLayout:
        orientation: 'lr-tb'
        padding: 10
        spacing: 5

        Button:
            text: 'S1'
            size_hint: .2,.1

        Button:
            text: 'S2'
            size_hint: .2,.1

        Button:
            text: 'S3'
            size_hint: .2,.1

        Switch:
            id: switch_id
            on_active: root.switch_on(self, self.active)
            size_hint: .2, .1



    '''))

我知道我需要添加以下代码,但我不确定如何使用类来实现。这是我提到的补充:

    def switch_on(self, instance, value):
        if value is True:
            print("Switch On")
        else:
            print("Switch Off")

任何有关如何正确地将这一切放在一起的帮助将不胜感激:)

标签: pythonkivykivy-language

解决方案


以下是如何执行此操作的示例:

from kivy.app import App
from kivy.lang import Builder



theRoot = Builder.load_string('''

StackLayout:
    orientation: 'lr-tb'
    padding: 10
    spacing: 5

    Button:
        text: 'S1'
        size_hint: .2,.1

    Button:
        text: 'S2'
        size_hint: .2,.1

    Button:
        text: 'S3'
        size_hint: .2,.1

    Switch:
        id: switch_id
        on_active: app.switch_on(self, self.active)
        size_hint: .2, .1

''')

class theApp(App):

    def build(self):
        return theRoot

    def switch_on(self, instance, value):
        if value is True:
            print("Switch On")
        else:
            print("Switch Off")


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

请注意,在kv字符串中,我使用的是 ,而不是root(这将是) ,它指的是类。StackLayoutapptheApp


推荐阅读