Kivy-课外的召唤方法

时间:2017-11-17 01:27:24

标签: python class kivy

我的.kv文件中有2个按钮和2个标签

<Controller>:
    lbl1: first_check
    lbl2: second_check

BoxLayout:
    orientation: 'horizontal'


    Button:
        on_press: root.start_program()
        text: 'Start Program'


    Button:
        on_press: root.stop_program()
        text: "Stop Program"


    Label:
        id: first_check
        text: 'No distance given'

    Label:
        id: second_check
        text: 'No distance given'

.py文件中,我有根小部件Controller类以及类外的一些其他函数check_distanceend_goal

def check_distance(dt):
"""The if statements in this block of code will be run if r.dist <= 2700"""
c = Controller()
r.loop()
print(r.dist)
if r.dist <= 2700:
    c.show_dist()
    time.sleep(0.5)
    r.loop()
    if r.dist <= 2700:
        c.lbl2.text = "Below 2700"
        end_goal()

def end_goal():
"""Stops the check_distance function from being called every 2 seconds then 
runs the next bit of code"""
    Clock.unschedule(check_distance)
    beepPin.write(1)
    time.sleep(1)
    beepPin.write(0)
    time.sleep(1)
    beepPin.write(1)
    time.sleep(1)
    beepPin.write(0)    

class Controller(BoxLayout):
    def __init__(self, **kwargs):
        super(Controller, self).__init__(**kwargs)



def start_program(self):
    """Tells the check_distance function to run every 2 seconds"""
    Clock.schedule_interval(check_distance, 2)



def stop_program(self):
    """Will stop the check_distance function from running"""
    Clock.unschedule(check_distance)
    self.lbl2.text = str(r.dist)

def show_dist(self):
    self.lbl1.text = str(r.dist)

class BaseMotorApp(App):
    def build(self):
        return Controller()

BaseMotorApp().run()

按下Start Program按钮后,每2秒调用check_distance函数。满足if条件后,它将运行所有check_distance代码。我知道这种情况正在发生,因为成功调用了end_goal。问题是c.show_dist()没有做任何事情,我没有收到任何错误。我想让它调用show_dist类中的Controller函数。我甚至试图一起消除show_dist函数,只是在self.lbl1.text = str(r.dist)函数中键入check_distance但仍然没有。我猜测我调用这个类方法的方式一定有问题。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

在Kivy应用程序中避免time.sleep

您遇到的问题是由于time.sleep。您应该将time.sleep替换为Kivy Clock.schedule_once,如下例所示。

def check_distance(dt):
    """The if statements in this block of code will be run if r.dist <= 2700"""
    c = Controller()
    r.loop()
    print(r.dist)
    if r.dist <= 2700:
        c.show_dist()
        Clock.schedule_once(check_distance_assign_label, 0.5)


def check_distance_assign_label(dt):
    r.loop()
    if r.dist <= 2700:
        c.lbl2.text = "Below 2700"
        end_goal()


def end_goal():
    """Stops the check_distance function from being called every 2 seconds then
    runs the next bit of code"""
    Clock.unschedule(check_distance)
    Clock.schedule_once(beepPinWrite(0), 1.0)
    Clock.schedule_once(beepPinWrite(1), 2.0)
    Clock.schedule_once(beepPinWrite(0), 3.0)


def beepPinWrite(index, dt):
    beepPin.write(index)