1

I am a beginner in Python and I am trying to create a timer in tkinter. I want to have a button which can stop the timer, however I just can't seem to figure out how to do this. I have tried researching about threads and classes but for such a simple task as a timer do I need these complicated concepts?

import tkinter as tk
from tkinter import *


def countdown(count):
    # change text in label
    label['text'] = count

    if count > 0:
        # call countdown again after 1000ms (1s)
        root.after(1000, countdown, count-1)


def stop():
    # THIS IS THE FUNCTION I WANT TO USE TO STOP THE TIMER, HOWEVER I DO NOT KNOW HOW, RIGHT NOT I HAVE JUST PUT exit() WHICH QUITS THE WHOLE PROGRAM
    countdown(exit())


root = tk.Tk()

root.geometry('600x600-200-0')

label = tk.Label(root)
label.place(x=35, y=15)

# call countdown first time
countdown(10)
# root.after(0, countdown, 5)

# Button, pressing it leads to greeting command
button = Button(text="OK", command=stop)
button.pack()

root.mainloop()

I was just wondering if there was a simple solution to this problem, as when I was researching all the tkinter stop timers had such complex code. Thank you in advance!

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • The universal [`after()`](https://web.archive.org/web/20190222214221id_/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html) method returns an integer identifier which you can pass to `after_cancel()` to prevent it from happening. – martineau Oct 19 '19 at 07:03
  • I'm really sorry I don't understand how I would implement this in my code, I have tried reading about the after method and I really can't grasp it – Python beginner Oct 19 '19 at 07:28

1 Answers1

2

You just need somewhere to store the job number from the after() function.

job = None

def countdown(count):
    # change text in label
    label['text'] = count

    if count > 0:
        global job
        # call countdown again after 1000ms (1s)
        job = root.after(1000, countdown, count-1)


def stop():
    global job
    if job:
        root.after_cancel(job)
        job = None
quamrana
  • 37,849
  • 12
  • 53
  • 71