Python - 一次移动两个乌龟对象

问题描述 投票:0回答:1

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

如有任何帮助,我们将不胜感激。

这是我的代码。 (第一部分归功于@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-graphics python-turtle
1个回答
2
投票

我绝不是 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

此代码创建一个函数,将第二只乌龟从其起始位置反复来回移动。它使用

ontimer
screen
方法来一遍又一遍地调度自己。稍微聪明一点的版本可能会检查一个变量以查看它是否应该退出,但我没有打扰。

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

turtle
模块继续!

© www.soinside.com 2019 - 2024. All rights reserved.