Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 724
Johnny Metz Avatar asked Nov 21 '25 05:11

Johnny Metz


2 Answers

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.

like image 92
slightlynybbled Avatar answered Nov 22 '25 19:11

slightlynybbled


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.

like image 28
Peter Gibson Avatar answered Nov 22 '25 18:11

Peter Gibson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!