A Display Name
A Display Name

Reputation: 367

How Do You Make Python Turtle Stop Moving?

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?

Upvotes: 2

Views: 16250

Answers (4)

GalaxyManBlue
GalaxyManBlue

Reputation: 1

I was working on this and I created this that works:

turtle.listen()
turtle.onkeypress(t.pu,'0') # i set it for 0 just because

this doesnt exactly stop the turtle, but it does stop the turtle from drawing more from the time you click.... It works for what I am using it for so thought I would share :)

Upvotes: 0

Have you tried to make the speed 0? using turtle.speed(0) If yes and for some reason it doesn't work you could also get the position of the turtle like so: turtle.position() and then do a while loop that keeps it on the same position with a goto: turtle.goto(its_position).

Upvotes: 0

Jones McKnight
Jones McKnight

Reputation: 11

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

Upvotes: 1

cdlane
cdlane

Reputation: 41872

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.

Upvotes: 1

Related Questions