Reputation: 11
I am working on a simple stopwatch. The problem is that the stopwatch automatically runs the moment you run the program and even if you press the stop button unable to make it stop.
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()
Upvotes: 0
Views: 129
Reputation: 4586
Your time counting is duplicated in two different methods:
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
only counts up if sw_started
is True
, but update_time
has no such check. The method you've scheduled with schedule_interval
is update_time
, so the value of sw_started
has no effect.
Either schedule update_clock
instead:
def on_start(self):
Clock.schedule_interval(self.update_clock, 0)
...or add a conditional to 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)
# [...]
Upvotes: 1