Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading