Python使用列表颜色制作 turtle 图形

标签 python list turtle-graphics

每次单击时,我都试图制作颜色变化的正方形。但是当我运行它时,它只填充红色。我怎样才能每次都改变颜色?

import turtle
t= turtle.Turtle()
s=turtle.Screen()
colors = ["red","orange","yellow","green","blue","indigo","purple"]
n=0

def square(x,y):
    t.penup()
    t.goto(x,y)
    t.pendown()
    t.color(colors[n])
    t.begin_fill()   
    for i in range(4):
        t.fd(90)
        t.lt(90)
    t.end_fill()
    t.penup()
if s.onscreenclick(square) == True:
    n+=1

最佳答案

您缺少对 s.mainloop() 的调用。如果您希望 n 随每次点击而改变,请在 square() 函数中将其声明为全局值,并在完成绘制后递增它。如果 n 大于 len(colors),请不要忘记将其重置为零。

s.onscreenclick() 的调用告诉 turtle “如何处理点击”(在本例中通过调用 square()),因此您不需要不需要放入 if 语句。

import turtle
t= turtle.Turtle()
s=turtle.Screen()
colors = ["red","orange","yellow","green","blue","indigo","purple"]
n=0

def square(x,y): # draw a square at (x,y)
    global n # use the global variable n
    t.penup()
    t.goto(x,y)
    t.pendown()
    t.color(colors[n])
    t.begin_fill()
    for i in range(4):
        t.fd(90)
        t.lt(90)
    t.end_fill()
    t.penup()
    n = (n+1) % len(colors) # change the colour after each square

s.onscreenclick(square) # whenever there's a click, call square()

s.mainloop() # start looping

最后一定要read this ,因为这是您第一次使用 StackOverflow。

关于Python使用列表颜色制作 turtle 图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51074566/

相关文章:

python - Round 函数不四舍五入?

python - 根据列表值选择 Pandas 行

python - 获得直方图的最大 y 值

r - 如何简化R中的嵌套列表?

python - 如何将指定的键+值移动到另一个字典

python - Mandelbrot 序列与 Python 的 Turtle

Python Tkinter postscript 错误大小导出

turtle-graphics - 如何移动LOGO中的 turtle ?

Python Scrapy 不会重试超时连接

c++ - 是否可以在一行中创建一个 std::list 并指定其值(C++)?