Search code examples
pythonmultithreadingflasktkintermultiprocessing

how to end flask app (e.g. control c) when i close/terminate a tkinter window


I am currently working on a python/flask project. I am using tkinter as a GUI for testing purposes to show variables and use sliders etc. However, I have been stuck on how to terminate both at the same time. Either I would get one of the not terminating after the other one does or i would get a EOFError: Ran out of input

Here is my current code:

### MAIN CODE FOR FLASK APP IS ABOVE ###

def flask_run():
    app.run(port=PORT)


def tk_run():
    root = tk.Tk()
    root.geometry("800x600")
    root.title("Telemate GUI")
    root.config(bg="#2c3e50")

    root.mainloop()


if __name__ == "__main__":
    flask_process = Process(target=flask_run)
    flask_process.start()

    root_process = Process(target=tk_run)
    root_process.start()

    flask_process.join()
    root_process.join()

I am using multiprocessing right now but i don't know if this is the best solution to run both tasks at the same time and terminate them (end the program/flask app when I terminate the tkinter) at the same time. Any help will be greatly appreciated


Solution

  • You can modify your code to gracefully terminate both Flask and Tkinter processes at the same time.

        try:
            flask_process.join()
            root_process.join()
        except KeyboardInterrupt:
            print("Terminating processes")
    
            if flask_process.is_alive():
                flask_process.terminate()
            if root_process.is_alive():
                root_process.terminate()
    
         
            flask_process.join()
            root_process.join()
    
        print("All processes terminated. Exiting.")