秒表停止和启动

2024-05-15 17:53:11 发布

您现在位置: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()

Tags: textselfidsiftimedefupdateroot
1条回答
网友
1楼 · 发布于 2024-05-15 17:53:11

您的时间计数采用两种不同的方法进行复制:

    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仅当sw_startedTrue时才计数,但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)
            # [...]

相关问题 更多 >