你如何让Python龟停止移动?

时间:2016-06-03 17:08:31

标签: python turtle-graphics

我已经尝试turtle.speed(0),我已经尝试turtle.goto(turtle.xcor(), turtle.ycor())似乎没有任何工作。

这就是守则:

import turtle

def stopMovingTurtle():
    ## Here I Need To Stop The Turtle ##

turtle.listen()
turtle.onkey(stopMovingTurtle, 'Return')
turtle.goto(-200, 0)
turtle.goto(200, 0)

那我怎么阻止它?

3 个答案:

答案 0 :(得分:1)

此处的问题不是turtle.listen()turtle.onkey()的顺序,而是在当前操作完成之前不会处理关键事件。您可以通过将长turtle.goto(-200, 0)动作细分为较小的动作来改善这一点,每个动作都允许您的关键事件有机会动作。这是一个粗略的例子:

import turtle

in_motion = False

def stopMovingTurtle():
    global in_motion
    in_motion = False

def go_segmented(t, x, y):
    global in_motion
    in_motion = True

    cx, cy = t.position()

    sx = (x > cx) - (x < cx)
    sy = (y > cy) - (y < cy)

    while (cx != x or cy != y) and in_motion:
        if cx != x:
            cx += sx
        if cy != y:
            cy += sy

        t.goto(cx, cy)

turtle.speed('slowest')
turtle.listen()
turtle.onkey(stopMovingTurtle, 'Return')

go_segmented(turtle, -200, 0)
go_segmented(turtle, 200, 0)

turtle.done()

如果(切换到窗口并且)点击返回,乌龟将停止绘制当前行。

答案 1 :(得分:0)

只需在“ Turtle代码”的末尾添加turtle.done()。缩进方式与turtle命令相同。

答案 2 :(得分:0)

您是否尝试将速度设为 0?使用 turtle.speed(0) 如果是,并且由于某种原因它不起作用,您也可以获得该职位 像这样的海龟:turtle.position() 然后做一个 while 循环,使其保持在与 goto 相同的位置:turtle.goto(its_position)

相关问题