如何在Dash应用程序上实现基于回调步骤进度的进度条?

问题描述 投票:0回答:1

我有以下 Dash 应用程序,我想实现一个进度条,单击按钮时会出现该进度条,并在每一步后更改其值。当在第 1 步时,它将显示 25%,当在第 2 步时,它将显示 50%,等等

import dash
from dash import dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import time

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Button('Run Process', id='run-button'),
    html.Div(id='output')
])

@app.callback(
    Output('output', 'children'),
    Input('run-button', 'n_clicks')
)
def run_process(n_clicks):
    if n_clicks is None:
        return html.Div()
    
    for i in range(4):
        # Simulating a process step
        time.sleep(1)
        step_text = f"Step {i+1} completed."
        print(step_text)
        result = 'This is the result'
    
    return result

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

我尝试使用 long_callbacks、全局变量和 dcc.Store 但没有成功。

python plotly-dash
1个回答
0
投票

稍微更新了我的回复以满足您的需求,您可以在这里找到原始回复。

您将需要为此使用后台回调。请参阅下面的代码更新版本,该版本应该可以工作:

import dash_bootstrap_components as dbc

import time
from uuid import uuid4
import diskcache
from dash import Dash, html, DiskcacheManager, Input, Output

launch_uid = uuid4()
cache = diskcache.Cache("./cache")

# Background callbacks require a cache manager
background_callback_manager = DiskcacheManager(
    cache, cache_by=[lambda: launch_uid], expire=60,
)

app = Dash(__name__, background_callback_manager=background_callback_manager)

app.layout = html.Div([
    html.Button('Run Process', id='run-button'),
    dbc.Row(children=[
        dbc.Col(
            children=[
                # Progress component sets up the loading bar
                dbc.Progress(id="progress-component", striped=True, value=5)
            ]
        ),
    ]
    ),
    html.Div(id='output')
])


def calculate_percent_progress(iteration, total):
    percent = int((iteration / total) * 100)
    f_percent = f"{int(percent)} %"
    return percent, f_percent


@app.callback(
    Output('output', 'children'),
    Input('run-button', 'n_clicks'),
    background=True,
    progress=[
        Output("progress-component", "value"),
        Output("progress-component", "label"),
    ],
)
def run_process(set_progress, n_clicks):
    if n_clicks is None:
        return html.Div()

    total = 4
    result = ""
    for i in range(total):
        # Simulating a process step
        time.sleep(1)
        step_text = f"Step {i + 1} completed."
        print(step_text)
        result = 'This is the result'

        # Update progress using set_progress
        percent, f_percent = calculate_percent_progress(iteration=i+1, total=total)
        set_progress([int(percent), f"{int(percent)} %"])

    return result


if __name__ == '__main__':
    app.run_server(debug=True, port=8055)
© www.soinside.com 2019 - 2024. All rights reserved.