Search code examples
pythonturtle-graphicspython-turtle

Python - Move Two Turtle Objects At Once


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)

Solution

  • 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!