Johnny Metz
Johnny Metz

Reputation: 6005

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:

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?

Upvotes: 3

Views: 14042

Answers (2)

slightlynybbled
slightlynybbled

Reputation: 2645

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.

Upvotes: 4

Peter Gibson
Peter Gibson

Reputation: 19564

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.

Upvotes: 1

Related Questions