Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python making turtle graphic by using list colors

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
like image 515
장재현 Avatar asked Jan 21 '26 23:01

장재현


1 Answers

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.

like image 88
Richard Inglis Avatar answered Jan 23 '26 13:01

Richard Inglis