我只想在短时间内更改变量的值!如果用户按下向上键/向下键,则该值应更改3秒钟。如何在Python中实现呢?
我已经尝试过诸如time.sleep()
之类的事情,但是使用这种方法,Tron这次并没有移动。
#Controls of Tron-Bike
#Up-Key increases the forward speed
def up():
thread_sleep_time = 0.5
# THIS code is ONLY for the POC (proof of concept)
# normally in TRON, the "bike" moves with a constant speed
# therefore you can use this hook
print("heading P1:", t1.heading())
我想更改thread_sleep_time
设置为0.5的代码,并在3秒钟后将其更改回1。
答案 0 :(得分:0)
您应该获得一个函数返回的值,该函数检查经过的时间并评估返回的值。
有关如何计算经过时间的提示:
import time
start_time = time.time()
elapsed_time = time.time() - start_time
答案 1 :(得分:0)
由于您专门标记了[turtle-graphics],因此这是一种使用乌龟计时器机制的方法。方法write()
连续运行将variable
的当前值打印到屏幕中央。当您按下向上箭头键时,另一个定时事件即会启动,将variable
更改为另一个值三秒钟,之后将其恢复为原始值。 write()
方法对此一无所知,只是不断显示 current 值:
from turtle import Screen, Turtle
from random import randint
FONT = ('Arial', 28, 'normal')
def up():
global variable
screen.onkey(None, "Up") # disable handler inside handler
screen.ontimer(lambda o=variable: reset_variable(o), 3000) # in milliseconds
variable = randint(1, 1000)
def reset_variable(original_value):
global variable
variable = original_value
screen.onkey(up, "Up") # restore event handler
def write():
turtle.undo()
turtle.write("variable = {}".format(variable), align='center', font=FONT)
screen.ontimer(write, 250)
variable = randint(1, 1000)
screen = Screen()
turtle = Turtle(visible=False)
turtle.write("variable = {}".format(variable), align='center', font=FONT)
screen.onkey(up, "Up")
screen.listen()
write()
screen.mainloop()