【问题标题】:tkinter button limit command to not repeattkinter 按钮限制命令不重复
【发布时间】:2019-03-14 18:33:13
【问题描述】:

您好,我正在尝试在 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)

【问题讨论】:

  • 如何在refresh_label 中禁用带有self.start['state'] = 'disabled' 的按钮?

标签: python tkinter


【解决方案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()

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 2018-01-24
    • 2019-07-14
    • 1970-01-01
    • 2016-01-28
    • 2017-12-23
    • 1970-01-01
    • 2018-08-11
    相关资源
    最近更新 更多