Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jupyter dropdown widget trigger action

I have a seemingly simple intention, just have a dropdown widget in jupyter notebook to trigger some simple action. It sort of works, but following script actually seems to trigger the event three times, what am I doing wrong?

import ipywidgets as widgets
from IPython.display import display, clear_output
vardict = ["var1","var2"]
select_variable = widgets.Dropdown(
    options=vardict,
    value=vardict[0],
    description='Select variable:',
    disabled=False,
    button_style=''
)
def get_and_plot(b):
    clear_output
    print(select_variable.value)

display(select_variable)
select_variable.observe(get_and_plot)

And the output when I select item from dropdown is something like

var1
var2
var2

and getting longer with each selection.

What I want to get is a way to trigger action (print or something else) only once per selection, how do I achieve this?

like image 301
kakk11 Avatar asked Mar 10 '23 11:03

kakk11


1 Answers

You need to specify which trait you are listening to. Right now you are listening to all the traits. When select an item on the dropdown, some private traits are being changed under the hood, which trigger the callback.

To avoid this, specify the trait you want to listen to with the names kwarg (can be either a trait name or a list of trait names)

select_variable.observe(get_and_plot, names='value')
like image 125
rmenegaux Avatar answered Mar 19 '23 06:03

rmenegaux