0

我想知道是否有一种方法可以制作颜色列表,例如shape_color = ['red', 'blue', 'green'],并将该列表分配给单个onkey()键盘键,以便每当我按下该键时,它会在颜色列表中循环,改变海龟的颜色?我的程序是 Python 海龟图形,您可以在其中移动光标,将不同的形状印入屏幕。

4

2 回答 2

0
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键时,您的填充颜色都会改变,在您定义的列表中循环。

于 2012-09-05T03:46:21.567 回答
0

@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()
于 2019-06-09T00:41:57.273 回答