python - 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)
解决方案
我相信问题在于您如何设置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()
推荐阅读
- wordpress - #wordpress。如何在数组中存储与数据库中的 $postid => $metavalue 相同的元键值
- ios - 如何将 pod(第三方框架)添加到我的自定义可可触摸框架中?
- python - 如何将 python serial.readline() 数据中的数据读入字符串
- ibm-cloud - IBM Watson Assistant:Facebook 页面的多工作区?
- wordpress - 如果未使用,带有 wordpress 的 Gatsby 找不到 ACF 灵活内容字段
- r - 将列表作为列名给出时的格式更改
- mysql - 数据显示顺序
- teamcity - Team City 条件构建执行
- vba - 使用一个按钮,我只想为一个选定的单元格添加值
- java - 如何在方法调用之间交替?