我需要隐藏一些组件,例如通过单击复选框(例如,图形或表格)。但是,该文档没有为此目的提供合适的部分。提前致谢!
最佳答案
您可以将需要隐藏的组件放置在 html.div([])
中并将其'display' 选项更改为'none' 在回调中。回调应该有一个下拉列表作为输入,html.div([])
中的组件作为输出。
以下是一个 Web 应用程序,仅包含一个下拉列表和一个根据下拉列表的值可见/隐藏的输入组件。 它应该在复制时直接工作:
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash('example')
app.layout = html.Div([
dcc.Dropdown(
id = 'dropdown-to-show_or_hide-element',
options=[
{'label': 'Show element', 'value': 'on'},
{'label': 'Hide element', 'value': 'off'}
],
value = 'on'
),
# Create Div to place a conditionally visible element inside
html.Div([
# Create element to hide/show, in this case an 'Input Component'
dcc.Input(
id = 'element-to-hide',
placeholder = 'something',
value = 'Can you see me?',
)
], style= {'display': 'block'} # <-- This is the line that will be changed by the dropdown callback
)
])
@app.callback(
Output(component_id='element-to-hide', component_property='style'),
[Input(component_id='dropdown-to-show_or_hide-element', component_property='value')])
def show_hide_element(visibility_state):
if visibility_state == 'on':
return {'display': 'block'}
if visibility_state == 'off':
return {'display': 'none'}
if __name__ == '__main__':
app.run_server(debug=True)
请注意,如果 html.div([])
中放置了多个组件,回调仍将仅更改它调用的组件的 'display' 属性输出。因此,您可以将其他 Dash 组件放置在同一个 Div 中,而不会影响它们的可见性。
希望这能正确回答您的问题。
更新(2020 年 5 月)
自从两年前给出这个答案以来,Dash 项目和用户文档已经有了很大的发展。文档现在显示了多种实现回调之间状态共享的方法,第一种方法是按照此答案的建议将数据存储在隐藏的 div 中。
请参阅文档中的特定页面 here .
关于python - 通过更新其他组件更改 Dash 组件的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50213761/