【问题标题】:Python - Move Two Turtle Objects At OncePython - 一次移动两个海龟对象
【发布时间】:2014-03-02 22:46:30
【问题描述】:

我想创建一个程序,其中一个海龟对象移动到用户单击鼠标的位置,而另一个海龟对象同时移动。我有第一部分,但我似乎无法让其余部分工作。

任何帮助将不胜感激。

这是我的代码。 (本文第一部分归功于@Cygwinnian)

from turtle import *
turtle = Turtle()
screen = Screen()
screen.onscreenclick(turtle.goto)
turtle.getscreen()._root.mainloop()

turtle2 = Turtle()
while True:
    turtle2.back(100)
    turtle2.forward(200)
    turtle2.back(100)

【问题讨论】:

  • 你能澄清一下你想让两只海龟同时移动是什么意思吗?我不认为 Python turtle 模块允许您同时移动多个事物,但是您可以在单击后让它们依次移动,或者让第二个海龟在移动第一个海龟的点击之间一直移动。
  • @Blckknght 是的,如果可能的话,第二个。我想“让第二只乌龟在移动第一只乌龟的点击之间一直移动。”感谢您一直以来的帮助。

标签: python turtle-graphics


【解决方案1】:

我绝不是 Python 的 turtle 模块的专家,但这里有一些我认为可以满足您需求的代码。只要第一只乌龟不在,第二只乌龟就会来回移动:

from turtle import *

screen = Screen() # create the screen

turtle = Turtle() # create the first turtle
screen.onscreenclick(turtle.goto) # set up the callback for moving the first turtle

turtle2 = Turtle() # create the second turtle

def move_second(): # the function to move the second turtle
    turtle2.back(100)
    turtle2.forward(200)
    turtle2.back(100)
    screen.ontimer(move_second) # which sets itself up to be called again

screen.ontimer(move_second) # set up the initial call to the callback

screen.mainloop() # start everything running

这段代码创建了一个函数,它使第二个海龟从其起始位置反复来回移动。它使用screenontimer 方法反复调度自己。稍微聪明一点的版本可能会检查变量以查看它是否应该退出,但我没有打扰。

这确实使两只海龟都移动了,但它们实际上并没有同时移动。在任何给定时刻,只有一个人可以移动。我不确定是否有任何方法可以解决这个问题,除了可能将移动分成更小的部分(例如,让海龟一次交替移动一个像素)。如果您想要更精美的图形,您可能需要从 turtle 模块继续前进!

【讨论】:

  • 绝对完美!真的非常感谢你!不确定这是否相关,但我使用的是 Python 2.7,我必须删除 screen.mainloop(),并在它工作之前简单地使用 mainloop()。
猜你喜欢
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多