我想知道是否有一种方法可以制作一个颜色列表,例如
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 对 @Aesthete 示例的修复的完整版本:
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()