【发布时间】:2018-04-30 17:08:13
【问题描述】:
我的.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_distance 和end_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 按钮时,check_distance 函数每 2 秒调用一次。一旦满足if 条件,它将运行所有check_distance 代码。我知道这是因为end_goal 被成功调用。问题是c.show_dist() 没有做任何事情,我没有收到任何错误。我希望它在Controller 类中调用show_dist 函数。我什至试图一起消除show_dist 函数,只是在check_distance 函数中键入self.lbl1.text = str(r.dist),但仍然没有。我猜我调用这个类方法的方式一定有问题。有人可以帮帮我吗?
【问题讨论】:
-
什么是
r???? -
这真的 self.lbl2.text = str(r.dist) 真的替换了文本吗?
-
@eyllanesc "r" 是从另一个模块导入的类实例。我发布的代码是一个缩短版本。
-
@乔伊。是的 self.lbl2.text = str(r.dist) 确实替换了文本。停止程序,但效果很好,并且确实做到了。