首页 > 解决方案 > python turtle.onkey() 在循环绑定错误

问题描述

我一直在尝试绑定数字键来更改颜色龟程序,当我尝试在循环中绑定它时,它只需要最后一种颜色。

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

但是如果我没有循环单独做就可以了

turtle.onkey(lambda: turtle.color(colors[1]), 1)
turtle.onkey(lambda: turtle.color(colors[2]), 2)
turtle.onkey(lambda: turtle.color(colors[3]), 3)

标签: pythonpython-3.xturtle-graphics

解决方案


我相信问题在于您如何设置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()

我发现functools.partial有时会使这种事情不易出错:

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

推荐阅读