问题
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