Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

python - Run GUI concurrently with Flask application

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...