while True:不与海龟一起工作

while True: not working with turtle

当我导入 turtle 时,尝试对其使用 while True: 循环,但它不起作用。这是代码:

import turtle
import time

stage = turtle.Turtle()

width = 900
height = 500

def up():
    turtle.setheading(90)
    turtle.forward(10)

def down():
    turtle.setheading(270)
    turtle.forward(10)

def char():
    turtle.listen()
    turtle.onkey(up, 'w')
    turtle.onkey(up, 's')

turtle.setup(width, height)
turtle.goto(390, 0)
char()

while True:
    if (turtle.ycor() >= 250):
        turtle.goto(460, 0) 

stage.goto(350, 0)
turtle.done()

我不知道为什么它不工作,它只是冻结(没有响应),然后没有错误消息。这真的很烦人,因为在我有 turtle 和 while true 循环的其他程序中也发生了同样的事情。

如果 True 是问题所在,还有其他方法 'forever check if',谢谢!

我不确切知道你需要完成什么,但你可以把

if (turtle.ycor() >= 250):
    turtle.goto(460, 0) 

在 up() 和 down() 内部。

虽然如果你需要永远拥有 运行 功能,正如你在评论中提到的,你可以将你的 while True: 东西放在第二个线程中,这应该让你的 window 冻结。

除了无限循环,您还可以使用任何例程来移动海龟,检查海龟是否已到达感兴趣的边界:

import turtle

WIDTH = 900
HEIGHT = 500

def up():
    turtle.setheading(90)
    turtle.forward(10)
    check()

def down():
    turtle.setheading(270)
    turtle.forward(10)
    check()

def check():
    if turtle.ycor() >= HEIGHT/2:
        turtle.goto(400, 0) 

turtle.setup(WIDTH, HEIGHT)

turtle.goto(350, 0)

turtle.listen()
turtle.onkey(up, 'w')
turtle.onkey(down, 's')

turtle.done()

另请注意,您的原始代码有两只乌龟,默认的一只和一只名为 stage 的乌龟 - 确保跟踪您正在操纵的乌龟!此外,在你的坐标系之上,你正在将海龟移出屏幕(除非那是你想要的)而无法将它移回屏幕。