Run GUI concurrently with Flask application

不想你离开。 提交于 2020-01-17 08:40:01

问题


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:

  • Start the flask web server
  • Open a tkinter GUI window with one button. When pressed, that button opens the app's index page (e.g. http://127.0.0.1:5000)
  • Terminate the flask web server when the tkinter gui window is closed

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?


回答1:


Options

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

  1. threading/multithreading
  2. separate applications

Multiple Threads

It is possible to write tkinter applications with multiple threads, but you must take care to do it.

  • tkinter must be run within the primary thread
  • tkinter cannot be accessed or implemented from any thread other than the primary

Separate Processes

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.




回答2:


I would suggest taking a look at the Klein web micro-framework which runs on Twisted Python. It's similar to Flask and may suit your needs and will allow you to run it all in a single process.

You can integrate it with the event loop of various UI toolkits, including tkinter.



来源:https://stackoverflow.com/questions/47169221/run-gui-concurrently-with-flask-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!