当我关闭/终止 tkinter 窗口时如何结束 Flask 应用程序(例如控制 c)

问题描述 投票:0回答:1

我目前正在开发一个 python/flask 项目。我使用 tkinter 作为 GUI 来进行测试,以显示变量并使用滑块等。但是,我一直困扰于如何同时终止两者。要么我得到一个在另一个终止后不终止,要么我得到一个

EOFError: Ran out of input

这是我当前的代码:

### 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()

我现在正在使用多处理,但我不知道这是否是同时运行两个任务并同时终止它们(当我终止 tkinter 时结束程序/flask 应用程序)的最佳解决方案。任何帮助将不胜感激

python multithreading flask tkinter multiprocessing
1个回答
0
投票

您可以修改代码以同时正常终止 Flask 和 Tkinter 进程。

    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.")
© www.soinside.com 2019 - 2024. All rights reserved.