Oct-07-2021, 05:02 AM
from tkinter import * def start(num): global sweepCancel print(num) if num < 10: num = num +1 sweepCancel=win.after(1000,start,num) def stop(): win.after_cancel(sweepCancel) win = Tk() InitButton = Button(win,text='start',command=lambda:start(0) , bg = "bisque2") InitButton.grid(row=0, column=1, pady = 20, padx = 10) ResetButton = Button(win,text='stop',command= stop , bg = "bisque2") ResetButton.grid(row=0, column=2, pady = 20) mainloop()Hello all,
I am trying to create a button to interrupt a function running in the background of tkinter. I looked through the web and found a few examples. Above is a snippet of code I got to work. The start button starts a function to count up and the stop button can halt the count. My first question is, is there a more elegant way to do this without having that global variable. I'm far from an expert in coding, but always heard global variables weren't good to use in pratice
My second question, my real application is slightly different than above. Instead of the if statement allowing the function to continue run, I wanted to call the after() command in a for loop. The code below is what I tried. Unlike the code above, the start button stays depressed and the window locks up. Any thoughts as to why? I sort of realize the above code is functionally no different than a for loop, but I'd rather the after() call a separate function (sweepFunction in this case) and not the original function (start). Thanks in advance!
from tkinter import * def sweepFunction(argument): print(argument) def start(): global sweepCancel for num in range(0,10): sweepCancel=win.after(1000,sweepFunction(num)) def stop(): win.after_cancel(sweepCancel) win = Tk() InitButton = Button(win,text='start',command=start , bg = "bisque2") InitButton.grid(row=0, column=1, pady = 20, padx = 10) ResetButton = Button(win,text='stop',command= stop , bg = "bisque2") ResetButton.grid(row=0, column=2, pady = 20) mainloop()