Search code examples
pythontaipy

How to split TaiPy GUI multi-page application where each page has its own file?


I want to simplify my multi-page Taipy GUI application by creating one Python file per page. Each new file should contain the Taipy Markdown page format and the custom Python code to manipulate variables used in the page.

The basic setup with one main.py file is explained here: https://docs.taipy.io/en/latest/getting_started/getting-started-gui/step_07/ReadMe/

How would I organize my Taipy multi-page application with one Python file per page?

What I tried initially was to create one Python file per page and move all custom code to set/manipulate variables and the page's Markdown format in the respective file.

The issue is that Taipy is unable to read variables or functions defined in the page's Python file. Only the page format is read. My next idea would be to set all variables in the application's main.py file, but that will bloat it up quite a lot in my view.


Solution

  • You can create multiple Scripts to divide your Markdown and Python code according to pages.

    Taipy GUI has a concept of Scope (Documentation). If you wrap your Markdown in the Markdown(...) object, Taipy can retrieve the variables and functions you have defined in these scripts. These values and functions has a Scope relative to your page. If you want global variables or functions (used in multiple pages), you must import them into your main.py.

    Here is a little example of an application using this Scope concept:

    page_1.py:

    value and the run() function have a Scope relative to the page_1. They can't be used on other pages (except if we import them into the main.py).

    from taipy.gui import Markdown
    
    value = 10
    
    page_1_md = Markdown("""
    <|{value}|slider|>
    
    <|Push|button|on_action=run|>
    """)
    
    def run(state):
        print("run")
    

    main.py:

    I import the Markdown object of page_1 to create my application.

    from taipy.gui import Gui
    from page_1 import page_1_md 
    
    pages = {
       "/":"<|navbar|>",
       "Page-1":page_1_md 
    }
    
    Gui(pages=pages).run()