-
Notifications
You must be signed in to change notification settings - Fork 949
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Example of binding similar handler to many widgets #1680
Comments
Thanks for submitting this. Something like this could potentially go in the Traitlet events section of the Widget events documentation. Ultimately, someone with more experience dealing with user issues (e.g. @jasongrout ) should decide whether there is value in this going into the documentation. Regardless of whether this is suitable for documentation, I think that there are a few things that could be improved with the snippet. I would avoid using As I understand, you are trying to use exec to dispatch the change to the correct list. An alternative would be to pass the list as a second argument to def on_text_change(change, list_to_change):
list_to_change.append(change['new']) You can then parametrize from ipywidgets import Text, HBox
t1 = Text(continuous_update=False)
t2 = Text(continuous_update=False)
result1, result2 = [], []
t1.observe(lambda change: on_text_change(change, result1), 'value', type='change')
t2.observe(lambda change: on_text_change(change, result2), 'value', type='change')
HBox([t1, t2]) As a further improvement, to avoid duplicating code and to make this more robust against possible future scope changes, you could use a loop across the number of widgets you want to make. from ipywidgets import Text, HBox
NUMBER_WIDGETS = 3
def instantiate_widget(description):
widget = Text(description=description, continuous_update=False)
result = []
widget.observe(lambda change: on_text_change(change, result), 'value', type='change')
return widget, result
widgets = []
results = []
for iwidget in range(NUMBER_WIDGETS):
widget, result = instantiate_widget(description=str(iwidget))
widgets.append(widget)
results.append(result)
HBox(widgets) |
+1 to adding some helpful section and more examples about registering handlers. Perhaps this could be a more complicated example, perhaps even showing how to do an interact-style dashboard manually. I like @pbugnion's version above too. |
I thought this example might be of use to others, since documentation is still (understandably) a weak point of ipywidgets. The title might be How to use a single handler for many equivalent widgets in a Box (e.g. input parameter guess values for a multi-parameter fit toolkit). Also the continuous_update example is missing in the docs. It took me quite some time to understand how to do both.
Sorry, perhaps it is not the best of codes, but it does what I intended.
The text was updated successfully, but these errors were encountered: