【问题标题】:Kivy Switch CallbackKivy 开关回调
【发布时间】:2019-03-09 06:58:04
【问题描述】:

我对 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")

任何关于如何正确地将它们组合在一起的帮助将不胜感激:)

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    下面是一个例子:

    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 字符串中,我使用的是app,而不是root(这将是StackLayout),它指的是theApp 类。

    【讨论】:

    • 这很有帮助。谢谢!!
    • 嘿,我今天才发现这个,你的工作确实帮助我找到了我的错误
    猜你喜欢
    • 2015-02-16
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多