How Do You Make Python Turtle Stop Moving?

10,183

Solution 1

Just add turtle.done() at the end of your "Turtle code". With the same indentation as the turtle commands.

Solution 2

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.

Share:
10,183
A Display Name
Author by

A Display Name

Updated on June 13, 2022

Comments

  • A Display Name
    A Display Name almost 2 years

    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?