Learning Python: Objective: Toggle between blue and red every 3 seconds.

Objective: Toggle between blue and red every 3 seconds.

Copy and Paste the python code into http://www.codeskulptor.org/


###################################################

import simplegui 

color = "Red"
counter=0

# Timer handler
def tick():
    global counter
    counter = counter + 1
    print str(counter)

# draw canvas
def draw(canvas):
    global counter
    ##python trick of flipping between even and odd
    if counter % 2 == 0:
        frame.set_canvas_background('Red')
    else:
        frame.set_canvas_background('Blue')

# Create frame and timer
frame = simplegui.create_frame("Counter with buttons", 200, 200)
frame.set_draw_handler(draw)
#first parameter is interval .. in this case, it is 3 seconds and starting to tick every counter which is 3 seconds
timer = simplegui.create_timer(3000, tick)

# Start timer
frame.start()
timer.start()


Explanation:


Step 1: Setup the frame work.

import simplegui
Create frame
Create timer - 3 seconds - 3000
Draw canvas

frame = simplegui.create_frame("Counter with buttons", 200, 200)
frame.set_draw_handler(draw)
#first parameter is interval .. in this case, it is 3 seconds and starting to tick every counter which is 3 seconds
timer = simplegui.create_timer(3000, tick)


Step 2

Setup ticker. Every tick equal to 3 seconds

def tick():
    global counter
    counter = counter + 1
    print str(counter)

Step 3: 

Start frame
Start Timer



The key on this exercise is draw function. The "counter%2 == 0" is how you determine if its even or odd

    if counter % 2 == 0:
        frame.set_canvas_background('Red')
    else:
        frame.set_canvas_background('Blue')




Alternative way to do it. Basically, flipping when Red to Blue, Red and Red. So, it does not really matter if its odd or even, the color going to take alternate to the tick.

import simplegui 

color = "Red"


# Timer handler
def tick():
    global color
    if color == "Red":
        color = "Blue"
    else:
        color = "Red"
    frame.set_canvas_background(color)
        
# Create frame and timer
frame = simplegui.create_frame("Counter with buttons", 200, 200)
frame.set_canvas_background(color)
timer = simplegui.create_timer(3000, tick)

# Start timer
frame.start()
timer.start()