与Flask应用程序同时运行GUI [英] Run GUI concurrently with Flask application

查看:298
本文介绍了与Flask应用程序同时运行GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试围绕我的烧瓶应用程序为办公室中的菜鸟创建一个简单的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终止flask应用程序:

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?

推荐答案

选项

flask应用程序阻止了您的GUI.您有两种选择:

Options

The flask application is blocking your GUI. You have two options:

  1. 线程/多线程
  2. 单独的应用

多线程

可以编写具有多个线程的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 thread
  • tkinter cannot be accessed or implemented from any thread other than the primary

我建议使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆