如何计算用户在给定时间内按下某个键的次数
How to count how many times a user presses a key in a given time
我正在尝试计算一个人按特定次数的按钮的次数。
import turtle
if random.randint(1,2) == 2:
turtle.listen()
turtle.onkey(number() ,'s')
else:
pass
def number():
global shots
shots += 1
shots 较早宣布。
这就是我所做的,但我需要设置某种类型的时间限制,因此用户只能按下它 4 秒,然后如果镜头大于某个数字,它就会执行某些操作。
请问有什么办法吗,谢谢
您可以使用turtle.ontimer
函数来实现一个定时器。在 timer
函数中,我递增全局时间变量并调用 turtle.ontimer(timer, t=100)
,它会在指定的计时器 t
.
后再次自动调用 timer
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()
我正在尝试计算一个人按特定次数的按钮的次数。
import turtle
if random.randint(1,2) == 2:
turtle.listen()
turtle.onkey(number() ,'s')
else:
pass
def number():
global shots
shots += 1
shots 较早宣布。
这就是我所做的,但我需要设置某种类型的时间限制,因此用户只能按下它 4 秒,然后如果镜头大于某个数字,它就会执行某些操作。
请问有什么办法吗,谢谢
您可以使用turtle.ontimer
函数来实现一个定时器。在 timer
函数中,我递增全局时间变量并调用 turtle.ontimer(timer, t=100)
,它会在指定的计时器 t
.
timer
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()