我正在尝试使用"onkeypress“,这是一个简单的代码,它创建了一个向前和向后的球,但它只向前移动。我是在Visual Studio代码上这样做的。
import turtle
import time
global i
i=False
wn=turtle.Screen()
wn.bgcolor("white")
wn.setup(width=600,height=600)
x=turtle.Turtle()
x.left(90)
x.shape("square")
x.color("black")
x.penup()
def start():
i=True
wn.onkeypress(start,"w")
wn.listen()
wn.update()
if i==True:
x.forward(100)
wn.mainloop()发布于 2020-03-20 05:30:27
这只是一个简单的错误。当您的代码运行时,它读取if i==True语句,观察i=False并到达end。当您按'w‘时,虽然您已将变量更改为True,但由于if语句已经传递,因此更改后该变量将不会执行任何操作。
相反,您可以将移动语句放入使用onkeypress附加的函数中
就像这样。
import turtle
import time
global i
i=False
wn=turtle.Screen()
wn.bgcolor("white")
wn.setup(width=600,height=600)
x=turtle.Turtle()
x.left(90)
x.shape("square")
x.color("black")
x.penup()
def start():
x.forward(100)
wn.onkeypress(start,"w")
wn.listen()
wn.update()
wn.mainloop()希望这能有所帮助。
发布于 2020-03-20 05:00:32
你只使用了x.forward(100),如果你想让它在多个方向上运行,你需要为每个方向编写更多的代码,比如x.left(100)
https://stackoverflow.com/questions/60763008
复制相似问题