Plotly Dash Dropdown is assymmetric

Hello,

I am having this dropdown annoyingly dragged back relative to the actual dropdown menu. Please suggest any correction where I can make it symmetric to the dropdown menu object.

I am using mulitpage Dash app without multiple pages and everything is in a single notebook. it works on colab and is sufficient for me.

This is my code:


app = Dash(external_stylesheets=[dbc.themes.DARKLY],suppress_callback_exceptions=True)

app.layout = html.Div(
    [
        dcc.Location("url",refresh=False),
        dcc.Dropdown(
            options=[
                {
                    "label": html.Span(style={'display':'inline-block'},
                        children=[
                            html.Br(),
                            dcc.Link("INDEX",href="/",style={'display':'inline','margin-left':'100px'})
                        ]
                    ),
                    "value": "index_layout"
                },
                {
                    "label": html.Span(style={'display':'inline-block'},
                        children = [
                            html.Br(style={'display':'block'}),
                            html.Img(
                                src="https://as2.ftcdn.net/v2/jpg/03/00/60/99/1000_F_300609989_u7T52hYtBKCrCbrPFc92crmcSjfUcL1N.jpg",
                                height=60,
                                style={'border-radius':'20px','display':'inline'}
                            ),
                            dcc.Link("MUSHROOM EDA",href="/mushroom",style={'display':'inline','margin-left':'50px'})
                        ]
                    ),
                    "value": "mushroom_layout"
                },
                {
                    "label": html.Span(
                        [
                            html.Br(style={'display':'block'}),
                            html.Img(
                                src="https://blog.logomyway.com/wp-content/uploads/2020/09/KFC-logo.jpg",
                                height=60,
                                style={'border-radius':'20px','display':'inline'}
                            ),
                            dcc.Link("KFC STOCK PRICE EDA",href="/kfc_stock",style={'display':'inline','margin-left':'50px'})
                        ]
                    ),
                    "value": "kfc_layout"
                },
                {
                    "label": html.Span(
                        [
                            html.Br(style={'display':'block'}),
                            html.Img(
                                src="https://cdn.who.int/media/images/default-source/mca/mca-covid-19/coronavirus-2.tmb-1366v.jpg?sfvrsn=4dba955c_19%201366w",
                                height=60,
                                style={'border-radius':'20px','display':'inline'}
                            ),
                            dcc.Link("COVID-19 EDA",href="/covid",style={'display':'inline','margin-left':'50px'})
                        ]
                    ),
                    "value": "covid_layout"
                }
            ],
            value="index_layout",
            id="main-page-dropdown",
            searchable=False,
            maxHeight=400,
            optionHeight=70,
            style={
                "height":140,
                'border-radius': '20px',
                'width':400,
                'display': 'flex',
                'flex-direction':'row',
                'justify-content': 'flex-end',
                'border-color': 'aqua',
            }
        ),
        html.Div(id="main-page-content",style={'display':'inline-flex','float':'left'})
    ],
    style={
        "font-family": "Monaco",
    }
)

msg = '''
This index page contain all the information on the datasets.

**Observations and Experiments carried:**

- Fitting tests were done on all the independent variables of each dataset. Top 10 Best Fits were plotted with interactive graphs.

- Inferences were drawn on each variable and the strength of the fit and fit was weighed for further explanations

- Machine Learning was impletmented for relevant datasets. Classification for Mushroom, Time Series analysis for kfc-stock and classification with geo location for covid-19.

- Different ML algorithms were used ranging from simple Linear Regression to complex Gradient Boosting bagging algorithms and Neural Nets.

'''

index_layout = html.Div(
    style={'display':'block','margin-top':400},
    children = [
        html.H1('INDEX',style={'border':'2px solid aqua','border-radius':'10px','display':'inline-block','margin-left':800,'padding':10}),
        dcc.Markdown(msg)
    ]
)


'''###########################################################################################################################################################'''
'''###################################################    MUSHROOM DATASET START   ###########################################################################'''
'''###########################################################################################################################################################'''


mushroom_layout = html.Div(
    children = [
        dcc.Dropdown(
            options=[
                {
                    'label': dcc.Link(f'Mushroom Index',href=f'/mushroom/mushroom_index',style={'display':'inline-block',"margin-left":'50px','margin-top':'15px','font-size':15}),
                    'value': 'mushroom_index'
                },
                {
                    'label': dcc.Link(f"Mushroom {cat_cols[0]}",href=f"/mushroom/mushroom_{cat_cols[0]}",style={'display':'inline-block',"margin-left":'50px','margin-top':'15px'}),
                    'value': 'mushroom_first_cat_col'
                },
                {
                    'label': dcc.Link(f'Mushroom {cat_cols[1]}',href=f'/mushroom/mushroom_{cat_cols[1]}',style={'display':'inline-block',"margin-left":'50px','margin-top':'15px'}),
                    'value': 'mushroom_second_cat_col'
                },
                {
                    'label': dcc.Link(f'Mushroom {cat_cols[2]}',href=f'/mushroom/mushroom_{cat_cols[2]}',style={'display':'inline-block',"margin-left":'50px','margin-top':'15px'}),
                    'value':'mushroom_third_cat_col'
                },
                {
                    'label': dcc.Link(f'Mushroom {cat_cols[3]}',href=f'/mushroom/mushroom_{cat_cols[3]}',style={'display':'inline-block',"margin-left":'50px','margin-top':'15px'}),
                    'value':'mushroom_fourth_cat_col'
                }
            ],
            value="mushroom_index",
            id="mushroom-dropdown-id",
            maxHeight=400,
            optionHeight=80,
            searchable=False,
            style={
                "height":80,
                'width':300,
                'border-radius': '12px',
                'display':'inline-block',
                'border-color': 'aqua',
                'align-items':'center',
                'margin-left':'50px',
                'margin-top': '50px'
            }
        ),
        html.Div(id="mushroom-page-content",style={'margin-top':'500px'})
    ]
)


mushroom_msg = '''

This dataset is a cleaned version of the original Mushroom Dataset for Binary Classification Available at UCI Library.
This dataset was cleaned using various techniques such as Modal imputation, one-hot encoding, z-score normalization, and feature selection.
It contains 9 columns:

- Cap Diameter
- Cap Shape
- Gill Attachment
- Gill Color
- Stem Height
- Stem Width
- Stem Color
- Season
- Target Class - Is it edible or not?
- The Target Class contains two values - 0 or 1 - where 0 refers to edible and 1 refers to poisonous.

'''

mushroom_index = html.Div(
    children=[
        html.H1('MUSHROOM EDA',style={'display':'block','margin-left':600,'width':400,'border':'2px solid aqua','padding':'10px','border-radius':'10px'}),
        html.Br(),
        dcc.Markdown(mushroom_msg)
        ]
    )

@callback(Output("main-page-content","children"),Input("main-page-dropdown","value"))
def display_main_page(value):
    return dict(
        index_layout=index_layout,
        mushroom_layout=mushroom_layout,
        kfc_layout=kfc_layout,
        covid_layout=covid_layout
    ).get(value)


app.run_server(debug=True)

Hi @H4CK3R

This is likely an issue with the CSS, but I canā€™t run your example. Could you make a complete self contained example that I can run and that reproduces the issue?

1 Like

Thaks for the swift response.

I reproduced a standalone code.This is a MultiPage App without multiple pages in folders.


# @title Installs

!pip install --quiet --upgrade "polars[all]"
!pip install --quiet duckdb
!pip install --quiet numpy
!pip install --quiet --upgrade fitter
!pip install --quiet pandas
!pip install --quiet --upgrade plotly
!pip install --quiet dash-bootstrap-components
!pip install --quiet jupyter-dash
!pip install --quiet dash
!pip install --quiet scipy
!pip install --quiet -U kaleido

import os,sys,time,re,glob
import numpy as np
import pandas as pd
import polars as pl
import duckdb as db
import polars.selectors as cs
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from scipy import stats
from fitter import Fitter,get_distributions
import dash
from dash import dcc, Input, Output, callback, html, page_container, page_registry, register_page, Dash, jupyter_dash, dash_table
jupyter_dash.default_mode = "external"
import dash_bootstrap_components as dbc
from typing import Literal,Optional
import plotly.io as pio
pio.templates["mod"] = go.layout.Template(layout=dict(font=dict(family="monaco"),yaxis=dict(showgrid=False),legend=dict(bgcolor="lightblue")))
pio.templates.default = "mod+plotly_dark"

app = Dash(external_stylesheets=[dbc.themes.DARKLY],suppress_callback_exceptions=True)

app.layout = html.Div(
    [
        dcc.Location('url',refresh=False),
        dcc.Dropdown(
            id = 'main-dropdown',
            options = [
                {
                    'label': html.Span(
                        style={'display':'inline_block'},
                        children = [
                            html.Br(),
                            dcc.Link('Index Landing Page',href='/',style={'display':'inline','margin-left':'50px'}),
                        ]
                    ),
                    'value':'index'
                },
                {
                    'label': html.Span(
                        style={'display':'inline'},
                        children = [
                            html.Br(),
                            html.Img(src='https://t4.ftcdn.net/jpg/00/97/58/97/240_F_97589769_t45CqXyzjz0KXwoBZT9PRaWGHRk5hQqQ.jpg',height=60,style={'border-radius':'20px','display':'inline'}),
                            dcc.Link('Go to Link 1',href='/link_1',style={'display':'inline','margin-left':'50px'}),
                        ]
                    ),
                    'value': 'link_1'
                },
                {
                    'label': html.Span(
                        style={'display':'inline'},
                        children = [
                            html.Br(),
                            html.Img(src='https://t4.ftcdn.net/jpg/00/97/58/97/240_F_97589769_t45CqXyzjz0KXwoBZT9PRaWGHRk5hQqQ.jpg',height=60,style={'border-radius':'20px','display':'inline'}),
                            dcc.Link('Go to Link 2',href='/link_2',style={'display':'inline','margin-left':'50px'}),
                        ]
                    ),
                    'value': 'link_2'
                }
            ],
            value='index',
            searchable=False,
            maxHeight=400,
            optionHeight=70,
            style={
                "height":140,
                'border-radius': '20px',
                'width':400,
                'display': 'flex',
                'flex-direction':'row',
                'justify-content': 'flex-end',
                'border-color': 'aqua',
            }
        ),
        html.Div(id ='main-page-content',style={'display':'inline-flex','float':'left'})
    ],
    style={'font-family':'Monaco'}
)

index_layout = html.Div("This is the Main Index Page")

link_1_layout = html.Div(
    [
        dcc.Dropdown(
            id = 'link-1-dropdown',
            options = [
                {
                    'label': dcc.Link('Link 1 Index Page',href='/link_1/link_1_index',style={'display':'inline-block',"margin-left":'50px','margin-top':'15px','font-size':15}),
                    'value': 'link_1_index'
                },
                {
                    'label': dcc.Link('Link 1 second page',href='/link_1/link_1_second_page',style={'display':'inline-block',"margin-left":'50px','margin-top':'15px'}),
                    'value': 'link_1_second_page'
                },
                {
                    'label': dcc.Link('Link 1 third page',href='/link_1/link_1_third_page',style={'display':'inline-block',"margin-left":'50px','margin-top':'15px'}),
                    'value': 'link_1_third_page'
                }
            ],
            value = 'link_1_index',
            maxHeight=400,
            optionHeight=80,
            searchable=False,
            style={
                "height":80,
                'width':300,
                'border-radius': '12px',
                'display':'block',
                'border-color': 'aqua',
                'align-items':'center',
                'margin-left':'300px',
                'margin-top': '50px'
            }
        ),
        html.Div(id = 'link-1-page-content',style={'margin-top':'500px'})
    ]
)

link_1_index_layout = html.H1("This is Link 1 Index Page")
link_1_second_page_layout = html.H1("This is Link 1 second page")
link_1_third_page_layout = html.H1("This is Link 1 third page")

@callback(Output('link-1-page-content','children'),Input('link-1-dropdown','value'))
def link_1_page_display(value):
    return dict(
        link_1_index = link_1_index_layout,
        link_1_second_page = link_1_second_page_layout,
        link_1_third_page = link_1_third_page_layout
    ).get(value)


link_2_layout = html.Div(
    [
        dcc.Dropdown(
            id = 'link-2-dropdown',
            options = [
                {
                    'label': dcc.Link('Link 2 Index Page',href='/link_2/link_2_index'),
                    'value': 'link_2_index'
                },
                {
                    'label': dcc.Link('Link 2 second page',href='/link_2/link_2_second_page'),
                    'value': 'link_2_second_page'
                },
                {
                    'label': dcc.Link('Link 2 third page',href='/link_2/link_2_third_page'),
                    'value': 'link_2_third_page'
                }
            ],
            value = 'link_2_index'
        ),
        html.Div(id = 'link-2-page-content')
    ]
)

link_2_index_layout = html.Div("This is Link 2 Index Page")
link_2_second_page_layout = html.Div("This is Link 2 second page")
link_2_third_page_layout = html.Div("This is Link 2 third page")

@callback(Output('link-2-page-content','children'),Input('link-2-dropdown','value'))
def link_2_page_display(value):
    return dict(
        link_2_index = link_2_index_layout,
        link_2_second_page = link_2_second_page_layout,
        link_2_third_page = link_2_third_page_layout
    ).get(value)


@callback(Output('main-page-content','children'),Input('main-dropdown','value'))
def main_page_display(value):
    return dict(
        index = index_layout,
        link_1=link_1_layout,
        link_2=link_2_layout
    ).get(value)



app.run_server(debug=True)

When you go into the link_1 page from the main dropdown and you click the link_1_dropdown the dropdown buttom is at one place and the menu is at different place. How do I solve this?. and also feel free to reduce any extra styling that might be the cause of problem. I was searching for the answer and ended up adding styles upon styles for all the options available. My reason for excessive styling is because when I set picture for a dropdown it usually aligns itself to top left so I had to use block displays and margin them to fit int he middle. I

My aim is to have dropdows next to each other with first dropdown having picture aligned perfectly in the center and second dropdown having its dropdown menu aligned symmetric to it. in a multipage dash app. I tried hard but couldnā€™t make it work. I appreciate all the suggestions.

Edit: I am a beginner to html/css. previously I could get by by adding dropdowns in graphs and using single page layout.

Thankyou very much.

Set the left margin of the div element rather than the dropdown

link_1_layout = html.Div(
    [
        dcc.Dropdown(
            id='link-1-dropdown',
            options=[
                {
                    'label': dcc.Link('Link 1 Index Page', href='/link_1/link_1_index',
                                      style={'display': 'inline-block', "margin-left": '50px', 'margin-top': '15px',
                                             'font-size': 15}),
                    'value': 'link_1_index'
                },
                {
                    'label': dcc.Link('Link 1 second page', href='/link_1/link_1_second_page',
                                      style={'display': 'inline-block', "margin-left": '50px', 'margin-top': '15px'}),
                    'value': 'link_1_second_page'
                },
                {
                    'label': dcc.Link('Link 1 third page', href='/link_1/link_1_third_page',
                                      style={'display': 'inline-block', "margin-left": '50px', 'margin-top': '15px'}),
                    'value': 'link_1_third_page'
                }
            ],
            value='link_1_index',
            maxHeight=400,
            optionHeight=80,
            searchable=False,
            style={
                "height": 80,
                'width': 300,
                'border-radius': '12px',
                'display': 'block',
                'border-color': 'aqua',
                'align-items': 'center',
                'margin-top': '50px'
            }
        ),
        html.Div(id='link-1-page-content', style={'margin-top': '500px'})
    ],
    style={'marginLeft': '300px'}  # set the margin here not in the "style" above for dcc.Dropdown
)
2 Likes

How can I avoid my whole page that is supposed to be load on id=ā€˜link-1-page-contentā€™?

also one more thing do you think its possible to place the second dropdown right next or at some length of right of the first dropdown?

Thankyou.

I solved it using Abosolute Positioning. Tried various methods using the display types, but when I was styling the whole page my graph also kept getting dragged into it.

Now I am using


style = dict(
    position='absoulte',
    top='100px',
    left='100px',
    width=400,
    height=100
)

positioning totally takes away the necessity to modify the display types as it gets confusing after you use multipages dash app.

I am open to changing solution using display types if anyone has solved it. right now giving this as solution.

Thankyou to @AnnMarieW and @PyGuy for giving suggestions

Hey @H4CK3R

Glad you got it working! I have one more suggestion for you. Since you are using dash-bootstrap-components, you can use the dbc.Row and dbc.Col components to precisely position things in the layout. Plus it enables a responsive design so it works with various screen sizes. It can replace most of things you currently have in the style prop.

You can find more info here:
https://dash-bootstrap-components.opensource.faculty.ai/docs/components/layout/

1 Like

Oh my god. When something is too vast I get lost in it fast. Thnakyou very much. THis is exactly what I need. Instead of using display types which complicates the children pages and absoulte positioing which require trial and error for coordinates. THis is exactly the simple solution that I need.

1 Like

Hey I actually went through some of the options of dbc and I decided i would stick with them cuz they are already better customized but I got stuck at one point.

How do you trigger the dbc.DropdownMenu or dbc.DropdownMenuItem? unlike in dcc.Dropdown we give the options a value and we filter with the value. but how should I filter the dbc callback input, for that matter what is the input that I should give in input callback of a dropdown?

I am attaching a code that I tried:


app = Dash(external_stylesheets = [dbc.themes.DARKLY],suppress_callback_exceptions = True)
ctx = dash.callback_context

app.layout = html.Div(
    [
        dcc.Location(id="url",refresh=False),
        dbc.DropdownMenu(
            [
                dbc.DropdownMenuItem(
                    "Index Page",href='/',id='index'
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 1",href='/link_1',id='link_1'
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 2",href='/link_2',id='link_2'
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 3",href='/link_3',id='link_3'
                )
            ],
            label="Main menu",
        ),
        html.Div(id='main-page-content')
    ]
)


index_layout = html.H1("This is the main Index page")

link_1_layout = html.Div(
    [
        dbc.DropdownMenu(
            [
                dbc.DropdownMenuItem(
                    "Link 1 Index Page",href='/link_1/link_1_index',id='link_1_index'
                ),
                dbc.DropdownMenuItem(
                    "Link 1 second page",href='/link_1/link_1_second_page',id='link_1_second_page'
                ),
                dbc.DropdownMenuItem(
                    "Link 1 third page",href='/link_1/link_1_third_page',id ='link_1_third_page'
                )
            ],
            label = "Link 1 Menu"
        ),
        html.Div(id='link-1-content')
    ]
)




link_1_index_page = html.H1("this is Link 1 index page")
link_1_second_page = html.H1("This is link 1 second page")
link_1_third_page = html.H1("This is link 1 third page")

@callback(
    Output('link-1-content','children'),
    Input('link_1_index','n_clicks')
)
def display_link_1_page(n_clicks):
    if n_clicks:
        return link_1_index_layout



@callback(
    Output('main-page-content','children'),
    Input('index','n_clicks')
)
def display_page(n_clicks):
    if n_clicks:
        index_layout




app.run_server(debug=True)

Edit figured it out

Ans:


@callback(
    Output('main-page-content','children'),
    [
        Input('index','n_clicks'),
        Input('link_1','n_clicks'),
        Input('link_2','n_clicks'),
        Input('link_3','n_clicks')
    ]
)
def display_page(*args):
    if not ctx.triggered:
        return index_layout
    else:
        button_id = ctx.triggered[0]['prop_id'].split('.')[0]

    if button_id == 'link_1':
        return link_1_layout
    elif button_id == 'link_2':
        return link_2_layout
    elif button_id == 'link_3':
        return link_3_layout
    else:
        return index_layout

other than the ctx.triggred ā€¦ code block for looking hideous dbc components are so good brother, insanely customizable

Great that you got it working :tada:

A couple more tips:

  1. If you would like to replace this:

You can use:

button_id = ctx.triggered_id

  1. When using dbc components, if you are looking for a regular dropdown, try the dbc.Select. If you need more features like multi select etc, you can still use dcc.Dropown

  2. If you would like to get rid of the entire callback, you can use Pages - it automatically serves the layout based on the url. Note - this isnā€™t obvious when you run the app in a cell of a notebook because you canā€™t see the url update in the address bar. Try running this as a regular python script as well and you will see how it works:

import dash
from dash import Dash, html
import dash_bootstrap_components as dbc

app = Dash(external_stylesheets = [dbc.themes.DARKLY],suppress_callback_exceptions = True, use_pages=True, pages_folder="")


index_layout = html.H1("This is the main Index page")

link_1_menu = dbc.DropdownMenu(
    [
        dbc.DropdownMenuItem(
            "Link 1 Index Page",href='/link_1'
        ),
        dbc.DropdownMenuItem(
            "Link 1 second page",href='/link_1/link_1_second_page'
        ),
        dbc.DropdownMenuItem(
            "Link 1 third page",href='/link_1/link_1_third_page'
        )
    ],
    label = "Link 1 Menu"
)

link_1_index_page = html.Div([link_1_menu, html.H1("this is Link 1 index page")])
link_1_second_page = html.Div([link_1_menu, html.H1("this is Link 1 second page")])
link_1_third_page = html.Div([link_1_menu, html.H1("this is Link 1 third page")])


dash.register_page("index", layout=index_layout, path="/")
dash.register_page("link_1_index_page", layout=link_1_index_page, path='/link_1/')
dash.register_page("link_1_second_page", layout=link_1_second_page, path='/link_1/link_1_second_page')
dash.register_page("link_1_third_page", layout=link_1_third_page, path='/link_1/link_1_third_page')

app.layout = html.Div(
    [
        dbc.DropdownMenu(
            [
                dbc.DropdownMenuItem(
                    "Index Page",href='/'
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 1",href='/link_1/'
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 2",href='/link_2'
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 3",href='/link_3'
                )
            ],
            label="Main menu",
        ),
        html.Hr(),
        dash.page_container
    ]
)

if __name__ == '__main__':
    app.run_server(debug=True)


1 Like

Sorry for responding late,
Yes that does make it easier, but I would like to also tell that I couldnā€™t find it anywhere in the docs or my sight has gone bad.
onece again Thankyou very much my code looks lot better and less clunky now.

oh so I can get rid of callbacks huh that actually saves lots of time but I need to first test it inside notebookā€¦I think youā€™ve motivated me to actually go through the whole documentation again. I just picked this up from last year so I am still rusty.

Howdy, I just tried your code in colab it doesnā€™t work, The url it gives

I tried this


%%writefile app_1.py

import dash
from dash import Dash, html
import dash_bootstrap_components as dbc

app = Dash(external_stylesheets = [dbc.themes.DARKLY],suppress_callback_exceptions = True, use_pages=True, pages_folder="")


index_layout = html.H1("This is the main Index page")

link_1_menu = dbc.DropdownMenu(
    [
        dbc.DropdownMenuItem(
            "Link 1 Index Page",href='/link_1'
        ),
        dbc.DropdownMenuItem(
            "Link 1 second page",href='/link_1/link_1_second_page'
        ),
        dbc.DropdownMenuItem(
            "Link 1 third page",href='/link_1/link_1_third_page'
        )
    ],
    label = "Link 1 Menu"
)

link_1_index_page = html.Div([link_1_menu, html.H1("this is Link 1 index page")])
link_1_second_page = html.Div([link_1_menu, html.H1("this is Link 1 second page")])
link_1_third_page = html.Div([link_1_menu, html.H1("this is Link 1 third page")])


dash.register_page("index", layout=index_layout, path="/")
dash.register_page("link_1_index_page", layout=link_1_index_page, path='/link_1/')
dash.register_page("link_1_second_page", layout=link_1_second_page, path='/link_1/link_1_second_page')
dash.register_page("link_1_third_page", layout=link_1_third_page, path='/link_1/link_1_third_page')

app.layout = html.Div(
    [
        dbc.DropdownMenu(
            [
                dbc.DropdownMenuItem(
                    "Index Page",href='/'
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 1",href='/link_1/'
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 2",href='/link_2'
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 3",href='/link_3'
                )
            ],
            label="Main menu",
        ),
        html.Hr(),
        dash.page_container
    ]
)

if __name__ == '__main__':
    app.run_server(debug=True)

then

!python app_1.py

maybe I should give additional arguments?

edit: Conceptually I understand how this works but I think I am missing some arguments. cuz I am thinking of sticking with this for my dash app. This is concise and less cluttered.

Hmm -this worked for me on colab. I didnā€™t include the wrtiefile and just ran the cell

1 Like

Hey thanks for trying that out!

I just ran without writing it to a script. So just to be clear we are doing the same thingā€¦

I ran the exact code block you posted without writefile magic in a colab notebook cell. did you do the same?

If yes I think there might be a version mismatch. cuz I am getting this error on running the code, it gives me error at register_page of index

---------------------------------------------------------------------------
LookupError                               Traceback (most recent call last)
<ipython-input-323-07735486f11d> in <cell line: 30>()
     28 
     29 
---> 30 dash.register_page("index", layout=index_layout, path="/")
     31 dash.register_page("link_1_index_page", layout=link_1_index_page, path='/link_1/')
     32 dash.register_page("link_1_second_page", layout=link_1_second_page, path='/link_1/link_1_second_page')

/usr/local/lib/python3.10/dist-packages/dash/_pages.py in register_page(module, path, path_template, name, order, title, description, image, image_url, redirect_from, layout, **kwargs)
    306     ```
    307     """
--> 308     if context_value.get().get("ignore_register_page"):
    309         return
    310 

LookupError: <ContextVar name='callback_context' at 0x7f60a4dd4a90>

and I am doing this at the start of my notebook

# @title Installs

!pip install --quiet --upgrade "polars[all]"
!pip install --quiet duckdb
!pip install --quiet numpy
!pip install --quiet --upgrade fitter
!pip install --quiet pandas
!pip install --quiet --upgrade plotly
!pip install --quiet dash-bootstrap-components
!pip install --quiet jupyter-dash
!pip install --quiet dash
!pip install --quiet scipy
!pip install --quiet -U kaleido

Edit:
This worked in a seperate colab then I understood where the error was coming from

import dash
from dash import dcc, Input, Output, callback, html, page_container, page_registry, register_page, Dash, jupyter_dash, dash_table
jupyter_dash.default_mode = "external"

I already gave the jupyter_dash as external for notebooks

I did see the same error one time, but in Runtime tab I selected Restart session it worked fine.

At the top of the file I only included:

!pip install dash
!pip install dash_bootstrap_components

Iā€™ll try that right now,
I just have one more question sorry to annoy you with further questions as chatgpt gives outdated and mostly inaccurate answers when it comes to dash and plotly in general

I gave my app layout inside a dcc.Loading instead of html.Div so that I wanted to have a loading page animation before every page loads up.

Its working as intended but with one caveat, that it still shows me ā€œLoadingā€¦ā€ text on the top left of page even tho I gave it animation then loading disappears then the dcc.Loading animation kicks in and does its intended job. do you know how to rectify/remove that loading text and give it only loading animation? I am giving you an example code.

app = Dash(external_stylesheets = [dbc.themes.DARKLY],suppress_callback_exceptions = True)
ctx = dash.callback_context

app.layout = dcc.Loading(
    [
        dcc.Location(id="url",refresh=False),
        dbc.DropdownMenu(
            [
                dbc.DropdownMenuItem(
                     html.Span([
                        html.Img(
                            src='https://t4.ftcdn.net/jpg/00/97/58/97/240_F_97589769_t45CqXyzjz0KXwoBZT9PRaWGHRk5hQqQ.jpg',
                            height=80
                        ),
                        html.Div("Index Page",style={'float':'right'})
                    ],style={'display':'inline-flex'}),href='/',id='index',active=True,style={'width':'800px','height':'100px'}
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 1",href='/link_1',id='link_1',style={'width':'800px','height':'100px'}
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 2",href='/link_2',id='link_2',style={'width':'800px','height':'100px'}
                ),
                dbc.DropdownMenuItem(
                    "Go to Link 3",href='/link_3',id='link_3',style={'width':'800px','height':'100px'}
                )
            ],
            label="Main menu",
            toggle_style={
                'height':'100px',
                'width':'800px',
            }
        ),
        html.Div(id='main-page-content')
    ],
    style=dict(display='inline-block',position='absolute',left='25vw',top='25vh')
)

index_layout = html.Div([html.H1("This is the main Index page")],style={'display':'block'})


@callback(
    Output('main-page-content','children'),
    [Input('index','n_clicks')]+[Input(f'link_{i+1}','n_clicks') for i in range(3)]
)
def display_page(*args):
    if not ctx.triggered:
        id = 'index'
    else:
        id = ctx.triggered_id
    time.sleep(3)
    if id == 'link_1':
        return link_1_layout
    elif id == 'link_2':
        return link_2_layout
    elif id == 'link_3':
        return link_3_layout
    else:
        return index_layout

app.run_server(debug=True)


No problem asking more questions - thatā€™s what the forum is for :slight_smile:

The dcc.Loading only works after the dash app is initialized. Normally thatā€™s pretty fast but in colab itā€™s slow.

Here is more information about customizing the ā€œLoadingā€¦ā€

1 Like

aight_meme

Thankyou very much for answering all. Ima explore with dash a little more, cuz I think I got all my questions answered and my code looks less cluttered with latest bits of code tips

3 Likes

hahaha Iā€™m going to frame that last one :rofl:

1 Like