How to count how many times a user presses a key in a given time

875 Views Asked by At

I'm trying to count the number of times a person presses a button a certain number of times.

import turtle         

if random.randint(1,2) == 2:
     turtle.listen()
     turtle.onkey(number() ,'s')

else:
    pass

def number():
   global shots
   shots += 1 

shots was declared earlier.

That's what I've done but I need to set some type of time limit, so the user can only press it for say 4 seconds then if shots are bigger than a number it's do something.

Is there any way to do this, thank you

1

There are 1 best solutions below

0
On BEST ANSWER

You can use the turtle.ontimer function to implement a timer. In the timer function I increment the global time variable and call turtle.ontimer(timer, t=100) which automatically calls timer again after the specified timer t.

import turtle


turtle.listen()

def number():
   global shots
   shots += 1
   print('Shots', shots)


def timer():
    global time
    time += .1  # Increase the global time variable.
    print(round(time, 1))
    if time < 2:  # 2 seconds.
       # Call `timer` function again after 100 ms.
       turtle.ontimer(timer, t=100)
    else:
       print('Time is up.')
       # Do something.

shots = 0
time = -0.1  # -0.1 because the `timer` adds .1 immediately.

timer()
turtle.onkey(number, 's')
turtle.mainloop()