tkinter鼠标点击计数器不会脱离我的倒计时循环



我正在尝试使用 python 编写一个小程序tkinter,以计算鼠标在 60 秒内单击按钮的次数,但我有一个问题:我无法打破倒计时循环

下面是我的代码:

from tkinter import *
class Application(Frame):
def __init__(self,master):
super(Application,self).__init__(master)
self.pack()
self.bttn_clicks = 0
self.createWidgets()
def createWidgets(self):
self.labelvariable = StringVar()
self.labelvariable.set("60")
self.thelabel = Label(self,textvariable = self.labelvariable,font=('Helvetica',50))
self.thelabel.pack(side=TOP)
self.firstButton = Button(self, text="Start", command=self.update_count)
self.firstButton.pack(side=TOP)
def update_count(self):
self.bttn_clicks += 1
self.firstButton["text"] = "Counter: " + str(self.bttn_clicks)
if self.bttn_clicks == 1:
countdown(1559)
def countdown(timeInSeconds):
mins, secs = divmod(timeInSeconds, 60)
timeformat = "{1:02d}".format(mins, secs)
app.labelvariable.set(timeformat)
root.after(1000, countdown, timeInSeconds-1)
if __name__ == '__main__':
root = Tk()
root.title("Timer")
app = Application(root)
root.mainloop()

我要做的是将所有内容都保留在类中。 使用外部函数只会使事情更难管理。

也就是说,您应该使用IntVar()而不是字符串 var,因为这将帮助我们跟踪时间。

我下面的代码将首先检查计时器是否为 60。如果是这样,则开始倒计时并添加到计数器。当计数器达到零时,按钮将禁用其命令,并且不再添加到计数器中。

我更改的另一件事是为计时器添加管理器方法。因为我们现在正在使用IntVar()所以我们需要做的就是一个get()命令,后跟一个-1和一个after()语句,以保持计时器运行到零。

我还清理了您的代码以遵循 PEP8 标准。

import tkinter as tk
class Application(tk.Frame):
def __init__(self,master):
super(Application,self).__init__(master)
self.bttn_clicks = 0
self.labelvariable = tk.IntVar()
self.create_widgets()
def create_widgets(self):
self.labelvariable.set(60)
self.thelabel = tk.Label(self, textvariable=self.labelvariable, font=('Helvetica',50))
self.thelabel.pack(side=tk.TOP)
self.firstButton = tk.Button(self, text="Start", command=self.update_count)
self.firstButton.pack(side=tk.TOP)
def update_count(self):
if self.labelvariable.get() == 60:
self.manage_countdown()
if self.labelvariable.get() != 0:
self.bttn_clicks += 1
self.firstButton.config(text="Counter: {}".format(self.bttn_clicks))
else:
self.firstButton.config(command=None)
def manage_countdown(self):
if self.labelvariable.get() != 0:
self.labelvariable.set(self.labelvariable.get() - 1)
self.after(1000, self.manage_countdown)

if __name__ == '__main__':
root = tk.Tk()
root.title("Timer")
app = Application(root).pack()
root.mainloop()

最新更新