Kivy秒表项目报错:Stopwatch对象无root属性该如何解决?
问题修复方案
错误原因
root是KivyApp类实例的专属属性,用于指向App加载的根控件,普通自定义控件类没有这个属性- 你代码中的
Stopwatch类本身就是kv文件声明的根布局类,kv中定义的带id的子控件已经绑定在self.ids字典中,不需要通过root属性访问
修复代码
只需要修改Stopwatch类中stopwatch方法的调用逻辑即可:
class Stopwatch(BoxLayout): def start_stopwatch(self): Clock.schedule_interval(self.stopwatch, 1) # 修正后的stopwatch方法 def stopwatch(self, *args): self.ids.counter.text = str(int(self.ids.counter.text) + 1)
可选优化
如果后续需要实现暂停功能,建议将Clock.schedule_interval返回的事件对象存储为实例属性,方便后续调用cancel()方法停止计时:
def start_stopwatch(self): # 存储计时事件对象 self.stopwatch_event = Clock.schedule_interval(self.stopwatch, 1) def stop_stopwatch(self): if hasattr(self, 'stopwatch_event'): self.stopwatch_event.cancel()
内容的提问来源于stack exchange,提问作者Gripen
相关产品推荐
相关产品推荐

