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!

S.G. Harmonia
  • 297
  • 2
  • 18
Minch
  • 87
  • 1
  • 2
  • 7

1 Answers1

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...

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • This is exactly what I was looking for. Thank you very much! – Minch Apr 21 '16 at 18:35
  • 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 – Petr Feb 14 '19 at 21:25
  • see this https://stackoverflow.com/questions/9776718/how-do-i-stop-tkinter-after-function – Petr Feb 14 '19 at 21:31