每次单击时,我都尝试用更改颜色来制作正方形。但是当我运行它时,它只会填充红色。如何每次更改颜色?
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
答案 0 :(得分:1)
您缺少对s.mainloop()
的呼叫。而且,如果您希望n
每次单击都更改,请在square()
函数中将其声明为全局变量,并在完成绘制后对其进行递增。如果n
大于len(colors)
,请不要忘记将其重置为零。
对s.onscreenclick()
的调用告诉乌龟“如何处理点击”(在这种情况下,通过调用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。
答案 1 :(得分:0)
我宁愿使用itertools中的cycle()
,而不是使用全局计数器和模数运算,而只是继续重复该列表:
from turtle import Turtle, Screen
from itertools import cycle
colors = cycle(["red", "orange", "yellow", "green", "blue", "indigo", "purple"])
def square(x, y):
screen.onscreenclick(None) # disable handler inside handler
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color(next(colors))
turtle.begin_fill()
for _ in range(4):
turtle.forward(75)
turtle.left(90)
turtle.end_fill()
turtle.penup()
screen.onscreenclick(square)
screen = Screen()
turtle = Turtle()
screen.onscreenclick(square)
screen.mainloop()
还请注意,我在处理程序的实现中禁用了onscreenclick()
处理程序,因此当上一个正方形仍在绘制时,用户无法单击,这会导致混乱的结果。