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

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

我在想,如果有一个办法可以让颜色列表,像shape_color = ['red', 'blue', 'green'],且分配给单个onkey()键盘密钥列表,以便每当我按下该键,它循环通过颜色列表,改变乌龟的颜色?我的计划是在你移动光标周围冲压不同形状到屏幕Python的乌龟图形。

python colors turtle-graphics
1个回答
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' @唯美主义者的榜样修复完全充实的版本:

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.