我在想,如果有一个办法可以让颜色列表,像shape_color = ['red', 'blue', 'green']
,且分配给单个onkey()
键盘密钥列表,以便每当我按下该键,它循环通过颜色列表,改变乌龟的颜色?我的计划是在你移动光标周围冲压不同形状到屏幕Python的乌龟图形。
shape_color = ['red', 'blue', 'green'] # list of colors
idx = 0 # index for color list
# Callback for changing color
def changecolor():
idx = (idx+1) % len(shape_color) # Increment the index within the list bounds
fillcolor(shape_color[idx]) # Change the fill color
# Register the callback with a keypress.
screen.onkey(changecolor, "c")
现在,每次你按下键c
,你的填充颜色会发生变化,通过你定义的列表循环。
的@jfs' @唯美主义者的榜样修复完全充实的版本:
from turtle import Screen, Turtle
from itertools import cycle
shape_colors = ['red', 'blue', 'green', 'cyan', 'magenta', 'yellow', 'black']
def change_color(colors=cycle(shape_colors)):
turtle.color(next(colors))
turtle = Turtle('turtle')
turtle.shapesize(5) # large turtle for demonstration purposes
screen = Screen()
screen.onkey(change_color, 'c')
screen.listen()
screen.mainloop()