Reputation: 1017
I'm sorry if that this is my second post in such a short period of time but I don't understand what is happening.
This is my code so far:
def countdown(self, remaining = None):
hours = int(self.hour.get())
minutes = int(self.minutes.get())
seconds = int(self.seconds.get())
if seconds == 0:
if minutes != 0:
seconds += 59
minutes -= 1
elif minutes == 0:
if hours != 0:
minutes += 59
seconds += 59
hours -= 1
else:
self.timerLab.configure(text="Times Up!")
else:
self.timerLab.configure(text="Time Remaining: %d:%d:%d " % (hours,minutes,seconds))
seconds -= 1
self.after(1000, self.countdown)
so this is a countdown timer that i have so far and i do not understand why seconds isn't updating. As far as my logic is concerned, if seconds -= 1 then it should take one and as it continues through the loop it should update. Am i right, or am I just completely being stupid and missing the obvious?
If any more of the code is needed please ask.
Upvotes: 1
Views: 182
Reputation: 20679
There are some problems here:
Entry
widget.after
is only called in the else
block, so when seconds == 0
it is not going to execute the method again.remaining
is always None, since you use the reference to the function without passing arguments.For the last problem, a quick fix would be change the last statement to self.after(1000, lambda: self.countdown(remaining))
, but there is an even better solution:
after
, and decrement there the variable used to represent the remaining seconds.divmod()
to easily conver the number of seconds to the format "h:m:s"
.The final result might look like this:
def start_countdown(self):
hours = int(self.hour.get())
minutes = int(self.minutes.get())
seconds = int(self.seconds.get())
self.remaining = hours * 3600 + minutes * 60 + seconds
self.countdown()
def countdown(self):
if self.remaining == 0:
self.timerLab.configure(text="Times Up!")
else:
m, s = divmod(self.remaining, 60)
h, m = divmod(m, 60)
self.timerLab.configure(text="Time Remaining: %d:%d:%d " % (h, m, s))
self.remaining -= 1
self.master.after(1000, self.countdown)
Upvotes: 1
Reputation: 133664
Calling seconds -= 1
at the end of the function is not going to do anything because you reset it on the next call to the value in the countdown timer. So you are basically setting the countdown timer to the exact same thing every time. Move that line above
self.timerLab.configure(text="Time Remaining: %d:%d:%d " % (hours,minutes,seconds))
And see what happens.
Upvotes: 2