[python] 파이썬 Dash에서 사용자 입력을 처리하는 방법은 어떻게 되나요?
- 사용자 입력을 받는 컴포넌트, 예를 들어
dcc.Input
이나dcc.Dropdown
을 레이아웃에 추가합니다.
import dash
from dash import html
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Input(id='input-box', type='text', value='Initial value'),
html.Button('Submit', id='submit-val', n_clicks=0)
])
- 콜백 함수를 사용하여 입력 값을 처리합니다.
@app.callback(
Output('output-container-button', 'children'),
[Input('submit-val', 'n_clicks')],
[state('input-box', 'value')])
def update_output(n_clicks, input_value):
if n_clicks > 0:
return 'The input value was "{}" and the button has been clicked {} times'.format(input_value, n_clicks)
위의 예제에서 @app.callback
데코레이터를 사용하여 update_output
콜백 함수를 정의하고 있습니다. 이 콜백은 submit-val
버튼의 클릭 횟수와 input-box
의 값을 입력값으로 받아 출력값을 업데이트합니다.
이러한 방식으로 파이썬의 Dash에서 사용자 입력을 처리할 수 있습니다.
더 자세한 내용은 다음 참조 문헌을 참고하세요:
- Plotly Dash Documentation: https://dash.plot.ly/
참조 코드
import dash
from dash import html
from dash.dependencies import Input, Output, State
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Input(id='input-box', type='text', value='Initial value'),
html.Button('Submit', id='submit-val', n_clicks=0),
html.Div(id='output-container-button',
children='Enter a value and press submit')
])
@app.callback(
Output('output-container-button', 'children'),
[Input('submit-val', 'n_clicks')],
[State('input-box', 'value')])
def update_output(n_clicks, input_value):
if n_clicks > 0:
return 'The input value was "{}" and the button has been clicked {} times'.format(input_value, n_clicks)
if __name__ == '__main__':
app.run_server(debug=True)