How Do You Make Python Turtle Stop Moving?

谁都会走 提交于 2019-12-02 11:21:22

问题


I've tried to do turtle.speed(0), and I've tried turtle.goto(turtle.xcor(), turtle.ycor()) nothing is seeming to work.

This Is The Code:

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)

So how do I stop it?


回答1:


The problem here isn't the order of turtle.listen() vs. turtle.onkey(), it's that the key event isn't being processed until the current operation completes. You can improve this by segmenting your long turtle.goto(-200, 0) motion into smaller motions, each of which allows a chance for your key event to act. Here's a rough example:

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()

If (switch to the window and) hit return, the turtle will stop drawing the current line.



来源:https://stackoverflow.com/questions/37619994/how-do-you-make-python-turtle-stop-moving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!