rho
rho

Reputation: 807

python turtle.onkey() in loop binding error

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)

Upvotes: 0

Views: 65

Answers (1)

cdlane
cdlane

Reputation: 41905

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()

Upvotes: 1

Related Questions