Countdown timer in python

Hi! I’m having trouble with a program that will start a countdown timer when a button is clicked. The problem is that the timer will start regardless if I clicked the button.

buttonPressed = False
start = False

def setup():
    size(500, 500)

def draw():
    global button, start, timeleft, timer
    background(0)
    if buttonPressed == False: # a button that is clicked to start the timer
        rect(200, 200, 100, 100)
    else: 
        timeleft = 10
        if start == True:
            timeleft = 10
        timer = Timer(timeleft)
        textSize(100)
        text(timer.remainingTime(), 220, 280)

class Timer:
    def __init__(self, duration):
        self.duration = duration
    def remainingTime(self):
        return max(0, self.duration - millis()/1000)
    
def mousePressed(c): 
    global buttonPressed
    if c.x > 200 and c.x < 300 and c.y > 200 and c.y < 300: # if the mouse presses the button
        buttonPressed = True
        start = True
           

Thank you in advance!

Try to move more of your logic into the Timer class. I’ve adapted your code here, removed the button hit area for clarity –

start = False

def setup():
    size(500, 500)
def draw():
    global timer
    background(0)
    if start:
        text(timer.remainingTime(), 220, 280)
    else:
        rect(200, 200, 100, 100)

class Timer:
    def __init__(self, duration):
        self.duration = duration
        self.start_time = millis()/1000
    def remainingTime(self):
        return self.duration - (millis()/1000 - self.start_time)
    
def mousePressed(): 
    global start, timer
    start = True
    timer = Timer(10)

But you might improve this further.

EDIT: substitute second() for millis()/1000

Thank you, this worked perfectly!