![](/img/trans.png)
[英]turtle.ontimer() equivalent for Zelle Graphics (python)?
[英]Python turtle wn.ontimer in an if statement
如下所示,我的代码中包含Turtle命令。 我想在if语句中的这些命令上放置一个计时器。 我当前的代码如下所示:
'#用户按下空格时,指示灯变为绿色
'#当光是绿色箭头移动50像素时
player1.pendown()
player1.forward(50)
player2.pendown()
player2.forward(50)
每次按空格键,箭头实际上只移动一次。 我想将其变成一个计时器,以便箭头每60毫秒移动一次,直到用户再次按下空格键。
我尝试使用wn.ontimer,但我一直在弄乱一些东西。 下面是代码的外观:
def advance_state_machine():
global state_num
if state_num == 0:
tess.forward(70)
tess.fillcolor("red")
state_num = 1
else:
tess.back(70)
tess.fillcolor("green")
state_num = 0
player1.pendown()
player1.forward(50)
player2.pendown()
player2.forward(50)
wn.onkey(advance_state_machine, "space")
wn.listen()
wn.mainloop()
您对问题的描述不一致,并且代码与您的描述不同步。 这是我认为您说过要执行的代码:
每60毫秒乌龟向前移动1步,每当按下空格键时,乌龟就会在红色/向前和绿色/向后交替。
我相信这段代码实现了,一个关键事件用于检测空格键,而一个计时器事件则用于使乌龟运动:
from turtle import Turtle, Screen, mainloop
def advance_state_machine():
global state_num
wn.onkey(None, 'space') # avoid overlapping events
if state_num > 0:
tess.fillcolor('green')
else:
tess.fillcolor('red')
state_num = -state_num
wn.onkey(advance_state_machine, 'space')
def advance_tess():
tess.forward(state_num)
wn.ontimer(advance_tess, 60)
wn = Screen()
tess = Turtle()
tess.fillcolor('red')
state_num = 1
wn.onkey(advance_state_machine, 'space')
wn.ontimer(advance_tess, 60)
wn.listen()
mainloop()
在尝试使用空格键之前,请确保单击该窗口使其处于活动状态。 如果无人看管,乌龟最终将离开屏幕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.