我希望根据所选的下拉窗口小部件选项更改文本框窗口小部件的描述。我以为我可以通过使用列表字典来实现这一点。这是我所做的一个例子:
#Lists of text box descriptions
LEF_SOL = ['AMP','DEP','LAGTIME']
INI_SOL = ['AMP','DEP','XWavemaker']
INI_REC = ['Xc','Yc','WID']
# dictionary made with such lists
wave_options = {'left boundary solitary':LEF_SOL,
'initial solitary wave':INI_SOL,'rectangular hump':INI_REC}
#dropdown widget of the dictionary
wave_maker = widgets.Dropdown(options=wave_options)
# Textbox 1 description = first object of list depending on the dropdown
first_option = widgets.BoundedFloatText(width = "20%",height = '50px',
description = wave_maker.value[0])
# Textbox 2 description = second object of list depending on the dropdown
second_option = widgets.BoundedFloatText(width = "20%",height = '50px',
description = wave_maker.value[1])
# Textbox 3 description = third object of list depending on the dropdown
third_option = widgets.BoundedFloatText(width = "20%",height = '50px',
description = wave_maker.value[2])
display(wave_maker,first_option,second_option,third_option)
然而,当我运行它时,文本框描述仍然属于下拉列表中显示的第一个选项。如果更改下拉列表,我希望它们更改。我知道这可以通过'link'来完成。看起来应该是这样的:
link((wave_maker,'value[0]'), (first_option, 'description'))
link((wave_maker,'value[1]'), (second_option, 'description'))
link((wave_maker,'value[2]'), (third_option, 'description'))
然而发生错误:
TypeError: <ipywidgets.widgets.widget_selection.Dropdown
object at 0x7fd47bbbd790> has no trait 'value[0]'
然而,当我将'link'更改为:
link((wave_maker,'value'), (first_option, 'description'))
然后出现此错误:
TraitError: The 'description' trait of a BoundedFloatText
instance must be a unicode string, but a value of ['AMP', 'DEP', 'XWavemaker']
<type 'list'> was specified.
我有办法解决这个问题吗?
答案 0 :(得分:0)
我发现我的问题的解决方案可以通过使用traitlets“观察”或“互动”来完成。我附上了一个“观察”的例子:
wave_options = ('INI_SOL', 'WK_IRR')
int_range = widgets.Dropdown(options=wave_options)
Xc_WK = widgets.BoundedFloatText()
DEP_WK = widgets.BoundedFloatText()
display(int_range,Xc_WK,DEP_WK)
def on_value_change(value):
if int_range.value == 'WK_IRR':
Xc_WK.description = 'Xc_WK'
DEP_WK.description='DEP_WK'
else:
Xc_WK.description ='amp'
DEP_WK.description='DEP'
int_range.observe(on_value_change, 'value')