Kivy Switch回调

时间:2018-10-04 00:23:31

标签: python kivy kivy-language

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

        <input class='button' id='square' type='button' onclick="loop4()" value='Draw Square' /> <br>

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

    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



    '''))

对于如何正确地将所有内容正确组合在一起的任何帮助,将不胜感激:)

1 个答案:

答案 0 :(得分:0)

以下是操作方法的示例:

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,而不是StackLayout(它是app),它指向{{1} }类。