我想知道是否有一种方法可以制作像shape_color = ['red', 'blue', 'green']
这样的颜色列表,并将该列表分配给单个按键功能按钮,这样每当我按下该按钮时,它会循环显示该列表颜色和改变海龟的颜色?该程序基本上是在Turtle Grapgics中,您可以在其中移动光标,并在屏幕上标记不同的形状。
答案 0 :(得分: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
键时,填充颜色都会发生变化,循环显示您定义的列表。
答案 1 :(得分: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()