python turtle.onkey() 循环绑定错误
python turtle.onkey() in loop binding error
我一直在尝试绑定数字键来改变颜色的乌龟程序,当我尝试在循环中绑定它时它只需要最后一种颜色。
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)
我认为问题在于您如何设置 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()
我一直在尝试绑定数字键来改变颜色的乌龟程序,当我尝试在循环中绑定它时它只需要最后一种颜色。
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)
我认为问题在于您如何设置 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()