简体   繁体   中英

Using drop down widget from ipywidgets

I am trying to use a drop down and store the selected value to a local variable. Although the print statement works, it's not storing the value to a variable. Any and all help will be highly appreciated.

import ipywidgets as widgets

bor = 'A'
drop_down = widgets.Dropdown(options=['A','B','C','D'],
                                description='Choose',
                                disabled=False)

def dropdown_handler(change):
        print(change.new)
        bor = change.new  # This line isn't working
drop_down.observe(dropdown_handler, names='value')
display(drop_down)

Relevant photo

Your function is working, but it assigns bor in the local namespace of the function, which is then lost when the function completes.

You will need to declare global bor in your dropdown_handler function. Then you should be able to call bor in the global namespace and get the result set by the dropdown.

import ipywidgets as widgets

bor = 'A'
drop_down = widgets.Dropdown(options=['A','B','C','D'],
                                description='Choose',
                                disabled=False)

def dropdown_handler(change):
    global bor
    print(change.new)
    bor = change.new  # This line isn't working
drop_down.observe(dropdown_handler, names='value')
display(drop_down)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM