如何通过列表改变Turtle中形状的颜色

问题描述 投票:0回答:2

我想知道是否有一种方法可以制作一个颜色列表,例如

shape_color = ['red', 'blue', 'green']
,并将该列表分配给单个
onkey()
键盘键,这样每当我按下该键时,它就会循环显示颜色列表,改变乌龟的颜色?我的程序是用 Python 海龟图形编写的,您可以在其中移动光标,将不同的形状印到屏幕上。

python turtle-graphics
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
键时,您的 填充颜色 都会改变,循环浏览您定义的列表。


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()
© www.soinside.com 2019 - 2024. All rights reserved.