[Solved] How to make an on/off switch for a function in a python program?


Take a look at this example:

from tkinter import *

root = Tk()

def run():
    global rep
    if var.get() == 1:
        print('Hey')
        rep = root.after(1000,run) #run the function every 2 second, if checked.
    else:
        root.after_cancel(rep) #cancel if the checkbutton is unchecked.

def step():
    print('This is being printed in between the other loop')

var = IntVar()
b1 = Checkbutton(root,text="Loop",command=run,variable=var)
b1.pack()

b2 = Button(root,text="Seperate function",command=step)
b2.pack()

root.mainloop()

after() method takes two arguments mainly:

  • ms – time to be run the function
  • func – the function to run after the given ms is finished.
  • after_cancel() method takes the variable name of after() only.

Perhaps also keep in mind, you can use root.update() and root.update_idletasks() with while loops, but its not efficient either.

Hope this helped you understand better, do let me know if any doubts or errors.

Cheers

9

solved How to make an on/off switch for a function in a python program?