Reputation: 41
Hello I'm trying to make a countdown timer app in tkinter and I'm using this class to make the button then to start the countdown. I'm quite new to python and also on tkinter.
The problem is after I press the button more than once it executes refresh_label more so it count downs faster.
How can I stop this from happening?
class Countdown():
def __init__(self,minutes, parent):
self.minutes = minutes
self.parent = parent
self.label = Label(parent,text='00:00',font=("Dense", 30),width=10,
bg= '#e74c3c')
self.label.place(x= 245, y= 330)
self.my_time = dt.time(0, self.minutes, 0)
self.var = 0
self.start = Button(self.parent,font=('Dense',15),text="Start", height = 4,
width = 51, fg = "#a1dbcd", bg="#e74c3c", command = self.refresh_label)
self.start.grid(row= 1,column=0, pady=415)
def refresh_label(self):
# This is the method that starts the countdown. I convert my_time
# from datetime.time object to datetime.datetime then i subtract
# a second in each 1000 ms and I refresh the text of the button
self.var += 1
second = (dt.datetime.combine(dt.date(1, 1, 1), self.my_time)-
dt.timedelta(seconds = self.var)).time()
self.label.configure(text=second)
self.label.after(1000, self.refresh_label)
Upvotes: 1
Views: 248
Reputation: 16958
I would disable the button after it is pressed, maybe until the pause or stop button is pressed.
To disable a button, you can do:
myButton['state'] = 'disabled'
or
from tkinter import DISABLED
mybutton['state'] = DISABLED
I would then change the call-back function of the button for start_button_pressed
:
self.start = tk.Button(self.parent, [...], command=self.start_button_pressed)
def start_button_pressed(self):
self.start['state'] = DISABLED
self.refresh_label()
Upvotes: 1