python - 秒表 - 停止和启动 Python
问题描述
我正在研究一个简单的秒表。问题是秒表会在您运行程序的那一刻自动运行,即使您按下停止按钮也无法使其停止。
class ClockApp(App):
sw_started = False
sw_seconds = 0
def update_clock(self, nap):
if self.sw_started:
self.sw_seconds += nap
def update_time(self, nap):
self.root.ids.time.text = strftime('[b]%H[/b]:%M:%S')
self.sw_seconds += nap
minutes, seconds = divmod(self.sw_seconds, 60)
self.root.ids.stopwatch.text = ('%02d:%02d.[size=40]%02d[/size]' % (int(minutes), int(seconds),
int(seconds * 100 % 100)))
def start_stop(self):
self.root.ids.start_stop.text = ('Start'
if self.sw_started else 'Stop')
self.sw_started = not self.sw_started
def reset(self):
if self.sw_started:
self.root.ids.start_stop.text = 'Start'
self.sw_started = False
self.sw_seconds = 0
def on_start(self):
Clock.schedule_interval(self.update_time, 0)
class ClockLayout(BoxLayout):
time_prop = ObjectProperty(None)
if __name__ == '__main__':
LabelBase.register(name='Roboto', fn_regular='Roboto-Thin.ttf', fn_bold='Roboto-Medium.ttf')
Window.clearcolor = get_color_from_hex('#101216')
ClockApp().run()
解决方案
您的时间计算以两种不同的方法重复:
def update_clock(self, nap):
if self.sw_started:
self.sw_seconds += nap # here
def update_time(self, nap):
self.root.ids.time.text = strftime('[b]%H[/b]:%M:%S')
self.sw_seconds += nap # and here
# [...]
update_clock
仅计数 if sw_started
is True
,但update_time
没有此类检查。您计划使用的方法schedule_interval
是update_time
,因此 的值sw_started
无效。
要么安排update_clock
:
def on_start(self):
Clock.schedule_interval(self.update_clock, 0)
...或添加条件update_time
:
def update_time(self, nap):
if self.sw_started:
self.root.ids.time.text = strftime('[b]%H[/b]:%M:%S')
self.sw_seconds += nap
minutes, seconds = divmod(self.sw_seconds, 60)
# [...]
推荐阅读
- python - 如何将图像上传到 django REST api?
- google-sheets - 获取给定范围内每行最后填充的单元格
- c++ - 在 2 个 dll 之间使用 QMap 时出现 LNK2005 和 LNK1169 错误
- javascript - 在帮助文件中时,Jest 模拟不运行
- java - Spring Dependency Mess - 与 Spring Boot 2.5.4 和 Spring Cloud 3.0.3 冲突
- groovy - 有没有办法在 Groovy 中的导入周围放置一个 try/catch 块?
- css - 将 ng-valid/invalid 类替换为 bootstrap .has-success/error 类
- mongodb - 自动删除在 Mongoose 中几毫秒后创建的令牌
- reactjs - 仅在满足条件时执行 componentDidMount()
- javascript - 尝试在 Angular 中路由到 404 页面时控制台出错