【问题标题】:How Do You Make Python Turtle Stop Moving?如何让 Python Turtle 停止移动?
【发布时间】:2016-10-03 20:26:17
【问题描述】:

我尝试过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)

那我该如何阻止呢?

【问题讨论】:

  • onkey 只是将一个函数绑定到一个键,所以你必须在之后listen 才能获得键。切换onkeylisten
  • 好的,但这对我的问题没有帮助。
  • 你试过了吗?我提出了切换turtle.listen()turtle.onkey() 顺序的想法,因为turtle.onkey 除了将函数绑定到键之外什么都不“做”,但listen 可以。
  • 我已经做到了,在我的代码中我输入了 print 来确认它并且它确实有效,我只需要知道如何阻止海龟移动......
  • 尝试同时使用.speed(0).goto

标签: python turtle-graphics


【解决方案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()

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2013-09-02
      • 2012-07-14
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多