2016-04-24 49 views
0

当我导入乌龟,然后尝试使用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() 

我不知道为什么它不工作,它只是冻结(没有响应),然后,没有错误信息。这真的很烦人,因为同样的事情发生在其他程序,我有乌龟,而真正的循环。

如果当真是问题时,有没有其他方法可以'永久检查',谢谢!

+1

你在哪里完成'while'循环? –

+0

当'turtle'在'(390,0)'时,为什么你会期望'turtle.ycor()> = 250',即当它的y坐标等于零? –

+0

因为你上下移动乌龟,但是我不能,因为窗口没有响应,你用W和S移动它,当它碰到顶部时,它会回落 –

回答

0

而不是你的无限循环,你可以有移动龟检查任何常规若龟已达到感兴趣的边界:

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的人 - 确保跟踪你操纵的乌龟!此外,坐在你的坐标系之上,你将乌龟从屏幕上移开(除非这是你想要的),无法将其移回屏幕上。

0

我不知道你要完成什么,但你很可能只是把

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

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

虽然如果您需要永久运行该功能,正如您在评论中提到的那样,您可以将第while True:件事放入第二个线程中,以防止窗口冻结。