0

I have been trying to bind number keys to change color turtle program, when i try to bind it in loop it only takes last color.

import turtle

colors = ('violet', 'indigo', 'blue', 'green', 'yellow', 'red', 'orange')
for i, c in enumerate(colors):
    turtle.onkey(lambda: turtle.color(c), i)

turtle.listen()
turtle.mainloop()

but works if I do it separately without loop

turtle.onkey(lambda: turtle.color(colors[1]), 1)
turtle.onkey(lambda: turtle.color(colors[2]), 2)
turtle.onkey(lambda: turtle.color(colors[3]), 3)
1
  • On running the program all i see is a blank window. Since I have not worked with turtle before could you elaborate what kind of output you're expecting while running the program Commented Aug 13, 2019 at 14:35

1 Answer 1

1

I believe the problem is in how you setup your lambda:

from turtle import Screen, Turtle

COLORS = ('violet', 'indigo', 'blue', 'green', 'yellow', 'red', 'orange')

screen = Screen()

turtle = Turtle('turtle')
turtle.shapesize(4)  # big turtle in center of screen

for number, color in enumerate(COLORS):
    screen.onkey(lambda c=color: turtle.color(c), number)

screen.listen()
screen.mainloop()

I find that functools.partial sometimes makes this sort of thing less error-prone:

from turtle import Screen, Turtle
from functools import partial

COLORS = ('violet', 'indigo', 'blue', 'green', 'yellow', 'red', 'orange')

screen = Screen()

turtle = Turtle('turtle')
turtle.shapesize(4)  # big turtle in center of screen

for number, color in enumerate(COLORS):
    screen.onkey(partial(turtle.color, color), number)

screen.listen()
screen.mainloop()
Sign up to request clarification or add additional context in comments.

1 Comment

it was obvious i couldn't see it "passing default value to lambda"! thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.