基本上,我正在努力制作一个小型游戏,用户必须在时间用完之前(5秒)多次点击按钮。
过了5秒后,按钮变灰/禁用。但是,我的代码无法正常工作,因为“计时器”仅在用户单击按钮时才起作用。无论用户是否单击了按钮,我都希望计时器能够运行。
所以基本上,当程序运行时,即使用户没有点击按钮并且已经过了5秒,该按钮也应该是灰色/禁用的。
这是我的代码:
from tkinter import *
import time
class GUI(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.result = 0
self.grid()
self.buttonClicks = 0
self.create_widgets()
def countTime(self):
self.end = time.time()
self.result =self.end - self.start
return (self.result)
def create_widgets(self):
self.start = time.time()
self.button1 = Button(self)
self.label = Label(self, text=str(round(self.countTime(),1)))
self.label.grid()
self.button1["text"] = "Total clicks: 0"
self.button1["command"] = self.update_count
self.button1.grid()
def update_count(self):
if(self.countTime() >=5):
self.button1.configure(state=DISABLED, background='cadetblue')
else:
self.buttonClicks+=1
self.button1["text"] = "Total clicks: " + str(self.buttonClicks)
root = Tk()
root.title("Something")
root.geometry("300x300")
app = GUI(root)
root.mainloop()
答案 0 :(得分:0)
你应该运行一个不同的线程(如此处所见:Tkinter: How to use threads to preventing main event loop from "freezing")来运行计时器。
检查另一个问题,以了解您的其他主题应该如何How to create a timer using tkinter?
答案 1 :(得分:0)
您必须使用after()
from tkinter import *
import time
class GUI(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.result = 0
self.grid()
self.buttonClicks = 0
self.create_widgets()
self.isRunning = True
self.update_clock()
self.master = master
def countTime(self):
self.end = time.time()
self.result =self.end - self.start
return self.result
def create_widgets(self):
self.start = time.time()
self.button1 = Button(self)
self.label = Label(self, text=str(round(self.countTime(),1)))
self.label.grid()
self.button1["text"] = "Total clicks: 0"
self.button1["command"] = self.update_count
self.button1.grid()
def update_count(self):
if self.isRunning:
self.buttonClicks+=1
self.button1["text"] = "Total clicks: " + str(self.buttonClicks)
def update_clock(self):
t = round(self.countTime(), 1)
self.label.configure(text=str(t))
if t < 5:
self.master.after(100, self.update_clock)
else:
self.isRunning = False
root = Tk()
root.title("Something")
root.geometry("300x300")
app = GUI(root)
root.mainloop()