虽然是真的:不是和屠呦呦一起工作

2024-10-05 21:53:14 发布

您现在位置:Python中文网/ 问答频道 /正文

当我导入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循环的其他程序中。在

如果问题是真的,有没有其他方法可以“永远检查”呢,谢谢!在


Tags: 代码importtruedefwidthstageforwardheight
2条回答

我不知道你到底需要完成什么,但是你可以把

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

内部向上()和向下()。在

尽管如您在评论中提到的,如果您需要让函数永远运行,您可以将while True:的东西放在第二个线程中,这样可以防止窗口冻结。在

如果海龟已经到达目标边界,您可以使用任何例程来移动海龟检查,而不是无限循环:

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请确保跟踪您正在操作的海龟!另外,在你的坐标系上,你把乌龟从屏幕上移开了(除非这是你想要的),但没有办法把它移回到屏幕上。在

相关问题 更多 >