0

How can I create a Tkinter GUI stop button to interrupt a function that takes a lot to be executed. I would like to be able to just hit the stop button and then it interrupts the main function and cleans all GPIOs. It would be cool if I could do it using the tk.after() instead of using threads. Thank you!

from Tkinter import *

def main_function():
    #a function that open and closes GPIOs on a RPi, and takes hours to be
#fully executed.

root = Tk()
root.title("Title")
root.geometry("500x500")

app = Frame(root)
app.grid()

start = Button(app, text="Start Scan",command=scanning)
stop = Button(app, text="Stop",command="break")

start.grid()
stop.grid()

Once I hit the start I need to wait the main function to end to be able to click the stop button.

Charles Wagner
  • 103
  • 1
  • 2
  • 10
  • 1
    first you have to run this long-running function in separated `thread` because normally it will block GUI and it will freeze so you can't press any button. – furas May 16 '19 at 17:29
  • Is there a way to do it not using thread, but Tk.after() ? – Charles Wagner May 16 '19 at 17:38
  • If your function is checking something in a loop then maybe you can use `after()` however if it requires a constant connection you might have no choice but to use threading. Threading is not that hard to use with tkinter. That said when you say it takes hours to execute is it sitting there with an open connection for hours or is it opening a connection checking for data then closing connection and repeating this process for hours? – Mike - SMT May 16 '19 at 17:48
  • It just takes hours to execute with an open connection running for hours.. – Charles Wagner May 16 '19 at 18:39
  • 1
    Depends on how your open connection actually runs, normally you can have a routine check for a stop flag, e.g. during every iteration in a for/while loop. If stop flag is True, return from the function immediately – Henry Yik May 17 '19 at 07:09
  • @CharlesWagner: Read [How do you run your own code alongside Tkinter's event loop?](https://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop) – stovfl May 18 '19 at 05:02

0 Answers0