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