Kivy Clock和条件语句

时间:2018-10-18 20:08:17

标签: python kivy kivy-language

我创建了变量timer_loop以连续运行。我想使用其他变量进行条件语句,但是我无法这样做。下面是一个示例,如果开关被激活,我将尝试每30分钟执行一次“操作”。任何反馈将不胜感激:)

from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
import datetime
import time

theRoot = Builder.load_string('''

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

    Label:
        text: "Zone 1 Valve"
        size_hint: .5, .1

    Switch:
        id: switch_id
        on_active: app.switch_on1(self, self.active)
        size_hint: .5, .1
''')

class theApp(App):

    def build(self):
        Clock.schedule_interval(self.timer_loop, 2)
        return theRoot

    def timer_loop(self, dt):  
        now_minute = int(time.strftime("%M"))

        if switch_on1.active & now.minute ==30 : # how do I use the varible switch_on1 in this loop for conditonal statements???
            print("Do something")
        else:
            print("Do nothing")

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

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

1 个答案:

答案 0 :(得分:0)

始终建议将类视为黑箱,我们可以建立输入并获得输出,并且可以通过属性来完成,例如,在这种情况下,您创建了StackLayout的活动属性,反映了switch_id的活动属性,由于theRootStackLayout对象,可以从python看到它,所以我们使用它:

from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
import time

theRoot = Builder.load_string('''
StackLayout:
    active: switch_id.active # <---
    orientation: 'lr-tb'
    padding: 10
    spacing: 5

    Label:
        text: "Zone 1 Valve"
        size_hint: .5, .1

    Switch:
        id: switch_id
        size_hint: .5, .1
''')

class theApp(App):
    def build(self):
        Clock.schedule_interval(self.timer_loop, 2)
        return theRoot

    def timer_loop(self, dt):  
        now_minute = int(time.strftime("%M"))
        if theRoot.active and now_minute == 30: # <---
            print("Do something")
        else:
            print("Do nothing")


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

您意识到没有必要使用switch_on1,因为主要条件是计时器的触发。