首页 > 解决方案 > 秒表 - 停止和启动 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()

标签: pythonkivy

解决方案


您的时间计算以两种不同的方法重复:

    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_startedis True,但update_time没有此类检查。您计划使用的方法schedule_intervalupdate_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)
            # [...]

推荐阅读