您好,我正在尝试在tkinter中创建一个倒数计时器应用程序,并且正在使用此类制作按钮然后开始倒数。我对python和tkinter还是很陌生。
问题是在我多次按下按钮之后,它多次执行了refresh_label,因此倒计时更快。
如何阻止这种情况发生?
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)
答案 0 :(得分:1)
按下按钮后,我可能会禁用它,也许直到按下暂停或停止按钮为止。
要禁用按钮,您可以执行以下操作:
myButton['state'] = 'disabled'
或
from tkinter import DISABLED
mybutton['state'] = DISABLED
然后,我将更改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()