Skip to content
Advertisement

how to stop tkinter timer function when i press button one more times?

i’d tried to use root.after_cancel(AFTER), but i dont know how.

    root.after_cancel(AFTER) 
AFTER = None
def countdown(count,time,name):
    global AFTER
    time['text'] =name,":",datetime.fromtimestamp(count).strftime("%%M:%%S")
    if count > 0 :
        AFTER = root.after(1000, countdown, count-1,time,name)
    elif count == 0 :
        time['text'] = f"Возрожден:{name}"``` 

Advertisement

Answer

It’s hard to guess what actually you are after, but … below working code which outputs to stdout and is able to start/stop/restart the countdown with pressing the [Countdown] button. The ‘trick’ is to run the timer all the time checking a value of a global variable, where pressing the button sets the value of that variable depending on what value it currently has. The way the code works appears to be an answer to both of your questions (1. how to stop and 2. how to reset the countdown by pressing the same button with which the countdown was started).

def countdown():
    global countdownValue
    if countdownValue > 0 :
        print(' countdown: ', countdownValue)
        countdownValue -= 1
    if countdownValue == 0 :
        countdownValue = -1
        print(f"n  Возрожден:  {name} :) ")
    root.after(1000, countdown)

def startStopCountdown():
    global countdownValue
    if countdownValue > 0:
        print('stopCountdown')
        countdownValue = -1
    else: 
        print('startCountdown')
        countdownValue = 10

import tkinter as tk
countdownValue = -1
name           = 'Возро'
    
root = tk.Tk()
root.title("3,2,1,...")
btn = tk.Button( root, text="Countdown", font=('',20), 
                 command=startStopCountdown)
btn.grid()
countdown()
root.mainloop()

By the way: in the context of your question following comes to my mind as maybe helpful in the context of your question Add a label/text (ideally positioned above a countdown timer) using tkinter .

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement