Change bootstrap theme using python

113 views Asked by At

I hope you are having a good day.

I'm trying in the Python code snippet below to change the theme while the app running. Is there a way to assign the theme to external_stylesheets argument? Is there a way to refresh the app?

P.S.:

The H5 component, and the returned value are for testing purpose only

Thank you, Best regards

import dash_bootstrap_components as dbc
from dash import Dash, dcc, html, Input, Output
import webbrowser as web

##### Constants #####
DASH_HOST = '127.0.0.1'
DASH_PORT = 8020
DASH_URL = 'http://' + DASH_HOST + ':' + str(DASH_PORT)

THEMES = \
    [
        dbc.themes.DARKLY,
        dbc.themes.LITERA,
        dbc.themes.MORPH,
        dbc.themes.QUARTZ,
        dbc.themes.SLATE,
        dbc.themes.SOLAR
    ]

THEME_MENU_OPTIONS = \
    {
        'DARKLY': dbc.themes.DARKLY,
        'LITERA': dbc.themes.LITERA,
        'MORPH': dbc.themes.MORPH,
        'QUARTZ': dbc.themes.QUARTZ,
        'SLATE': dbc.themes.SLATE,
        'SOLAR': dbc.themes.SOLAR
    }

theme = THEMES[0]
app = Dash(title='Weather Forecast', external_stylesheets=[theme])

theme_picker = dcc.Dropdown(
    options=
    [
        {'label': k, 'value': v}
        for k, v in THEME_MENU_OPTIONS.items()
    ],
    value=THEMES[0],
    clearable=False,
    id='theme_picker',
    style={
        "color": "black"
    }
)
    
app.layout = dbc.Card(
    [
        html.H5(
            id='h5'
        ),
        theme_picker
    ]
)


@app.callback(
    Output('h5', 'children'),
    Input('theme_picker', 'value'),
)
def change_theme(value):
    global app

    app = Dash(title='Weather Forecast', external_stylesheets=[value])

    return value



##### Open app #####
web.open(DASH_URL, new=0, autoraise=True)

if __name__ == '__main__':
    app.run(port=DASH_PORT, debug=True)
0

There are 0 answers