I'm trying to make squares with change color each time when I click. but when I run this, it only fills out red color. How can I change color each times?
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
You're missing a call to s.mainloop(). And if you want n to change with each click, declare it as global within the square() function, and increment it after you finish drawing. Don't forget to reset n to zero if it gets larger than len(colors).
The call to s.onscreenclick() is telling the turtle 'how to handle a click' (by calling square() in this case), so you don't need to put into an if statement.
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
Finally, be sure to read this, as it's your first time on StackOverflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With