I would like to make simple click speed test in Python (tkinter).My actual code looks like that:
from tkinter import *
import time
def coutdown():
t = 5
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
if t==0:
print("Finish !!!")
break
#window configuration
screen= Tk()
screen.title("Click Speed Test")
screen.configure(width= 500, height= 300)
screen.configure(bg='lightblue')
canvas = Canvas(screen, width=500, height=500)
#text
text= Label(screen, text= "Click Speed Test")
text.config(font= ("Courier", 16))
text.pack()
text_v2= Label(screen, text= "Click the button to start the game!")
text_v2.config(font= ("Courier", 10))
text_v2.pack(ipady= 10)
# start button
turn_on= Button(screen, text="Start", command= coutdown)
turn_on.pack(ipadx=10, ipady= 5, pady= 5, padx= 100)
#click button
click= Button(screen, text="Click!!!")
click.pack(ipadx=6, ipady= 8, pady= 5, padx= 5)
screen.mainloop()
I have big problem with buttons. I made fuction: coutdown, which is to calculate time and I set it as a command to start button. Second button will be use to click on it after start the game, but now it hasn't a command. My vision look like that: When I will start the game by "Start" button, I will have 5 seconds to click "Click" button as many as I can. After 5 seconds script will shut down and and the result will display. But now if I click start button, all script freezes and I can't click any button. Do you know how to fix it?
I tried to change my timer but all the time script works wrong.
CodePudding user response:
Hope this helps:
from tkinter import *
import time
num = 0
tm = 0
def count():
global num
if tm:
num = 1
def coutdown():
global tm
tm = time.time()
def refresh():
global tm, num
dif = time.time() - tm
if tm and dif > 5:
print("Finish !!!", num, 'clicks')
num = 0
tm = 0
elif tm:
mins, secs = divmod(int(dif), 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
screen.after(1, refresh)
#window configuration
screen= Tk()
screen.title("Click Speed Test")
screen.configure(width= 500, height= 300)
screen.configure(bg='lightblue')
canvas = Canvas(screen, width=500, height=500)
#text
text= Label(screen, text= "Click Speed Test")
text.config(font= ("Courier", 16))
text.pack()
text_v2= Label(screen, text= "Click the button to start the game!")
text_v2.config(font= ("Courier", 10))
text_v2.pack(ipady= 10)
# start button
turn_on= Button(screen, text="Start", command= coutdown)
turn_on.pack(ipadx=10, ipady= 5, pady= 5, padx= 100)
#click button
click= Button(screen, text="Click!!!", command= count)
click.pack(ipadx=6, ipady= 8, pady= 5, padx= 5)
#screen.mainloop()
refresh_var = screen.after_idle(refresh)
mainloop()