[英]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)
I believe the problem is in how you setup your lambda
: 我相信问题在于您如何设置
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: 我发现
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.