Python - Move Two Turtle Objects At Once

依然范特西╮ 提交于 2019-12-09 23:24:10

问题


I would like to create a program where one turtle object moves to where a user clicks their mouse, and a different turtle object moves at the same time. I have the first part, but I can't seem to get the rest to work.

Any help would be appreciated.

This is my code. (Credit for the first part of this goes to @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)

回答1:


I am by no means an expert at Python's turtle module, but here's some code that I think does what you want. The second turtle will be moving back and forth any time the first turtle is not:

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

This code creates a function that moves the second turtle repeatedly back and forth from its starting position. It uses the ontimer method of the screen to schedule itself over and over. A slightly more clever version might check a variable to see if it is supposed to quit, but I didn't bother.

This does make both turtles move, but they don't actually move at the same time. Only one can be moving at any given moment. I'm not sure if there is any way of fixing that, other than perhaps splitting up the moves into smaller pieces (e.g. have the turtles alternate moving one pixel at a time). If you want fancier graphics you probably need to move on from the turtle module!



来源:https://stackoverflow.com/questions/22134712/python-move-two-turtle-objects-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!