Search code examples
pythonpython-3.xturtle-graphicsarrow-keys

Is there a way to keep drawing a square with one turtle while, at the same time, moving another turtle with the arrow keys?


I am trying to move a drawing slowly across the screen as I move another turtle with the arrow keys. The problem is that my code only makes the drawing move across the screen, not allowing me to move the other turtle with the keys. I have tried defining the keys inside of the while true statement and it still came out with the same outcome.

Here is my code:

from turtle import * 
setup(500, 500)
Screen()
screen = Screen()
title("Turtle Keys")
turtle1 = Turtle() 
turtle2 = Turtle()

def moving_square():
    turtle1.fillcolor("Red")
    turtle1.begin_fill()
    for i in range(4):
        turtle1.forward(50)
        turtle1.right(90)
    turtle1.end_fill()
turtle1.goto(-350, 0)
turtle1.pendown()
turtle1.hideturtle()

def k1():
    turtle2.forward(50)

def k2():
    turtle2.left(45)

def k3():
    turtle2.right(45)

def k4():
    turtle2.back(25)

onkey(k1, "Up")
onkey(k2, "Left")
onkey(k3, "Right")
onkey(k4, "Down")

while True:
    moving_square()
    screen.update()         
    turtle1.forward(5)

Solution

  • It needs listen() to react on pressed keys.

    And you have this information even in documentation for onkey()

    from turtle import * 
    
    # --- functions ---
    
    def moving_square():
        turtle1.fillcolor("Red")
        turtle1.begin_fill()
        for i in range(4):
            turtle1.forward(50)
            turtle1.right(90)
        turtle1.end_fill()
        
    def k1():
        turtle2.forward(50)
    
    def k2():
        turtle2.left(45)
    
    def k3():
        turtle2.right(45)
    
    def k4():
        turtle2.back(25)
    
    # -- main ---
    
    setup(500, 500)
    Screen()
    screen = Screen()
    title("Turtle Keys")
    turtle1 = Turtle() 
    turtle2 = Turtle()
    
    turtle1.goto(-350, 0)
    turtle1.pendown()
    turtle1.hideturtle()
    
    onkey(k1, "Up")
    onkey(k2, "Left")
    onkey(k3, "Right")
    onkey(k4, "Down")
    
    listen()
    
    while True:
        moving_square()
        screen.update()         
        turtle1.forward(5)