与 Flask 应用程序同时运行 GUI [英] Run GUI concurrently with Flask application
问题描述
我正在尝试围绕我的烧瓶应用程序为我办公室的新手构建一个简单的 tkinter GUI 窗口.我希望脚本按以下顺序执行这些任务:
I'm trying to build a simple tkinter GUI window around my flask application for noobs in my office. I want the script to perform these tasks in the following order:
- 启动flask web服务器
- 一键打开 tkinter GUI 窗口.按下后,该按钮会打开应用的索引页面(例如 http://127.0.0.1:5000)莉>
- 在 tkinter gui 窗口关闭时终止 Flask Web 服务器
这是我目前所拥有的,但应用程序独立于 tkinter 窗口运行,我必须在看到 gui 窗口之前使用 crtl+c 终止烧瓶应用程序:
This is what I have so far but the app runs independently of the tkinter window and I must terminate the flask app using crtl+c before I even see the gui window:
from flask_app import app
from tkinter import tk
import webbrowser
class GUI:
def __init__(self):
app.run()
self.btn = tk.Button(root, text='Open in Browser', command:self.open_browser_tab).pack()
def open_browser_tab(self):
webbrowser.open(url='http:127.0.0.1:5000', new=2)
if __name__ == '__main__':
root = tk.Tk()
GUI(root)
root.mainloop()
那么如何在应用程序运行时运行进程?
So how can I run a process while the app's running?
推荐答案
Options
flask 应用程序阻止了您的 GUI.您有两个选择:
Options
The flask application is blocking your GUI. You have two options:
- 线程/多线程
- 单独的应用程序
多线程
可以用多线程编写 tkinter
应用程序,但你必须小心去做.
Multiple Threads
It is possible to write tkinter
applications with multiple threads, but you must take care to do it.
tkinter
必须在主线程中运行tkinter
不能从主线程以外的任何线程访问或实现
tkinter
must be run within the primary threadtkinter
cannot be accessed or implemented from any thread other than the primary
我建议使用 subprocess
模块.如果您将我们的功能分成两个应用程序,并使用 subprocess 模块来启动/停止 Flask 应用程序,我想您将拥有您想要的.
I would recommend using the subprocess
module. If you separate our your functionality into two applications and use the subprocess module to start/stop the flask application, I think you will have what you want.
这篇关于与 Flask 应用程序同时运行 GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!