flashing button that stops flashing when pressed in Tkinter, without using flash()

Viewed 20

I am new to tkinter, I am trying to make a button that flashes green and silver until it is pressed, at which point it reverts to silver. I followed the code from this website, flash button example, it seemed to be closest to what I was trying to do.

%reset -f
import tkinter as tk

    
root = tk.Tk()

def stop_flash():
    print('stop_flash')
    root.after_cancel(flasher2)
    root.after_cancel(flasher1)

button = tk.Button(root, text="Hello", command=stop_flash, background='silver', activebackground='red')
button.pack()

def flash():

    button.configure(background = 'green')
    flasher1 = root.after(500, lambda: button.configure(background = 'silver'))
    flasher2 = root.after(1000, flash)

flasher1 = root.after(500, lambda: button.configure(background = 'silver'))
flasher2 = root.after(1000, flash)
root.mainloop()

I got the button to flash but I don't understand why it won't stop. I have tried making a separate switch button so I would only need to use 1 after() function but it gets even messier. Any help here would be greatly appreciated!!!!!

0 Answers
Related