【问题标题】:How to change color of shapes in Turtle through lists如何通过列表更改 Turtle 中形状的颜色
【发布时间】:2012-08-29 07:51:52
【问题描述】:

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

【问题讨论】:

  • 我希望我的问题足够清楚。
  • 你的问题很清楚,你绝对可以这样做。 What have you tried?
  • 我尝试设置一个等于 0 的变量并尝试 +1,但到目前为止我还没有运气。
  • 向我们展示您的代码!只需将其添加到您的问题中,我们就可以为您提供解决方案。

标签: python turtle-graphics


【解决方案1】:
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 键,您的填充颜色都会改变,循环显示您定义的列表。

【讨论】:

  • 它会引发 UnboundLocalError。您可以使用:changecolor = lambda colors=itertools.cycle(shape_color): fillcolor(next(colors))
  • 很好的答案,如果你提交我会删除我的。
【解决方案2】:

@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-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多