我正在开发
dash
应用程序。我想提供接受用户的 multiple
值(最好用逗号分隔)的功能。
目前正在尝试,通过使用带有
input
的 type=text
框,用户通过手动键入 comma
来输入值,如下所示,在回调中,我将其获取为 str
,我需要将其转换为 list
作为最终结果,将进一步用于计算。
# Input in textbox
-1, "", "na", "#99", 100
# Received in callback
val='-1, "", "na", "#99", 100'
# Output
[-1, "", "na", "#99", 100]
import dash
from dash import Dash
import dash_bootstrap_components as dbc
dbc_css = (
"https://cdn.jsdelivr.net/gh/AnnMarieW/[email protected]/dbc.min.css"
)
app = Dash(
__name__,
suppress_callback_exceptions=True,
external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css],
)
btn1 = dbc.Button(id='btn1', children='click')
ip1 = dbc.Input(id='ip1', type='text')
div1 = html.Div(id='div1')
@app.callback(
Output('div1', 'children'),
Input('btn1', 'n_clicks'),
State('ip1', 'value'),
prevent_initial_call=True,
)
def get_values_and_process(n, val):
status = False
if n is None:
raise PreventUpdate
print(f"{val=}")
print(f"{type(val)}")
# proposed(trying to do this way)
# get the input value which is string and convert into list and then use it further
return status
app.layout = dbc.Container(html.Div([btn1, ip1, div1]))
if __name__ == "__main__":
app.run(host="0.0.0.0", port="8001", debug=True)
我尝试在 dash 中搜索内置组件来实现此功能,但没有成功。有没有更好的方法来避免用户不输入逗号来实现此目的?
如果我理解正确的话,你只需要把一个字符串变成一个列表。考虑到您已经用逗号分隔您的值, split 方法可能是最好的选择。
val='-1,"","na","#99",100'
val = val.split(",")
这会将你的字符串变成一个列表。