Pan Yan
Pan Yan

Reputation: 1720

In IPython Widgets, how to update the DropDown widget with new value?

I created a DropDown widget:

self.foo_widget = widgets.Dropdown(description='Lorem ipsum', width=100)
self.foo_widget.options = ['Default', 'A', 'B', 'C', 'D']

And I capture the on_trait_change event:

self.foo_widget.on_trait_change(self.handler, 'value')

Now in the handler function handler, I want set the DropDown value back to 'Default'. But the following code only changes the value without updating the widget display. The DropDown still shows the original selection value (e.g., 'C') even though print self.foo_widget.value shows to be 'Default'.

self.foo_widget.value = 'Default'

Is this a bug of IPython Widget? What is the correct way to cause the update of the view?

In fact, for the list widgets, it seems I have to clear the options and assign options again to cause the widgets' display to update. Anyone has similar experience?

Update: the answer by nluigi below works great. As shown in the following example.

class test(object): 
    def __init__(self):
        self.foo_widget = widgets.Dropdown(description='Lorem ipsum', width=100)
        self.foo_widget.options = ['Default', 'A', 'B', 'C', 'D']
        self.foo_widget.on_trait_change(self.handler, 'value')
        display(self.foo_widget)

    def handler(self, name, old, new):
        print(self.foo_widget.value)
        print(self.foo_widget.selected_label)
        self.foo_widget.value = 'Default'
        self.foo_widget.selected_label = 'Default'

Upvotes: 8

Views: 3628

Answers (1)

nluigi
nluigi

Reputation: 1345

Per the specification of the selection class, you must also set the selected_label attribute to 'Default' to have the widget update:

self.dropDown.value = 'Default'
self.dropDown.selected_label = 'Default'

Upvotes: 6

Related Questions