2

My aim is to create a simple timer program. It updates itself constantly until the stopButton is pressed. However, I am unsure how to stop the tick function from running so that the timer stays the same once the stopButton is pressed.

This is my code so far:

import tkinter

root = tkinter.Tk()
root.title('Timer')
root.state('zoomed')

sec = 0

def tick():
    global sec

    sec += 0.1
    sec = round(sec,1)
    timeLabel.configure(text=sec)
    root.after(100, tick)

def stop(): 
    # stop the timer from updating.

timeLabel = tkinter.Label(root, fg='green',font=('Helvetica',150))
timeLabel.pack()

startButton = tkinter.Button(root, text='Start', command=tick)
startButton.pack()

stopButton = tkinter.Button(root, text='Stop', command=stop)
stopButton.pack()

root.mainloop()

What would be a possible way of stopping the tick() function?

Any help would be greatly appreciated!

1 Answer 1

3

You can have another global that tracks whether you should currently be counting ticks. If you aren't supposed to be counting ticks, just have tick do nothing (and not register itself again).

import tkinter

root = tkinter.Tk()
root.title('Timer')
root.state('zoomed')

sec = 0
doTick = True

def tick():
    global sec
    if not doTick:
        return
    sec += 0.1
    sec = round(sec,1)
    timeLabel.configure(text=sec)
    root.after(100, tick)

def stop():
    global doTick
    doTick = False

def start():
    global doTick
    doTick = True
    # Perhaps reset `sec` too?
    tick()

timeLabel = tkinter.Label(root, fg='green',font=('Helvetica',150))
timeLabel.pack()

startButton = tkinter.Button(root, text='Start', command=start)
startButton.pack()

stopButton = tkinter.Button(root, text='Stop', command=stop)
stopButton.pack()

root.mainloop()

There are other structural improvements that could be made (using a class to get rid of the globals) and style improvements (snake_case instead of camelCase), but this should get you pointed in the right direction...

Sign up to request clarification or add additional context in comments.

3 Comments

This is exactly what I was looking for. Thank you very much!
this has a design flaw. if you call stop and then call start again before the timer expires the next interval will not be correct period. In fact you may get 2 events instead of 1 so the timing will break. You should use return value to cancel the event

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.