当我按下“ w”键创建行走动画后,我想制作两张彼此重叠的图片:
#Imports
import turtle
import time
#Registers Gifs
turtle.register_shape("ZeldaBackToolless1.gif")
turtle.register_shape("ZeldaBackToolless2.gif")
Zelda = turtle.Turtle()
Zelda.penup()
def move_up():
if Waiting == True:
time.sleep(.2)
Zelda.shape("ZeldaBackToolless1.gif")
Waiting = False
else:
time.sleep(.2)
Zelda.shape("ZeldaBackToolless2.gif")
Waiting = True
turtle.listen()
turtle.onkeypress(move_up, "w")
我认为,如果有一种方法可以在move_up()
函数中使用布尔语句保存以前处于哪个状态的布尔语句,那会很好用。
答案 0 :(得分:0)
正如我不愿建议的那样,在此编程级别的简单方法是使用全局状态变量:
waiting = True
def move_up():
global waiting
time.sleep(.2)
if waiting:
Zelda.shape("ZeldaBackToolless1.gif")
else:
Zelda.shape("ZeldaBackToolless2.gif")
waiting = !waiting
更简短的是,您可以将标志用作列表索引:
waiting = True
def move_up():
global waiting
display = ["ZeldaBackToolless1.gif", "ZeldaBackToolless2.gif"]
waiting = !waiting
time.sleep(.2)
Zelda.shape(dislpay[waiting])
答案 1 :(得分:0)
我认为您的解决方案和@Prune的解决方案都考虑不周。通过使用time.sleep()
,您可以阻止其他乌龟事件。如果最终将其用作 wait 图像,那么您最后要做的就是阻止您正在等待的东西。实际上,应该使用计时器事件来完成此操作:
from turtle import Screen, Turtle
def walk():
screen.onkeypress(None, "w") # disable handler in handler
def stop_walk():
zelda.shape("image_2.gif")
screen.onkeypress(walk, "w") # restore event handler
zelda.shape("image_1.gif")
screen.ontimer(stop_walk, 200) # in the future, in milliseconds
screen = Screen()
# Registers Gifs
screen.register_shape("image_1.gif")
screen.register_shape("image_2.gif")
zelda = Turtle()
zelda.penup()
screen.onkeypress(walk, "w")
screen.listen()
screen.mainloop()
这将使其他海龟事件在等待期间继续发生。