ipywidgets widgets values not changing

拜拜、爱过 提交于 2020-03-02 06:50:47

问题


I am trying to get output from my ipywidgets widgets in Microsoft Azure Notebooks running Jupyter Notebooks in Python 3.6. However, it does not return new values when I get them. This also applies to the event handlers/interact never being called for other widgets.

I have tried putting in different initial values, using different types of widgets (Text, Textarea, Checkbox, Button, ToggleButton). I have tried getting the w.value, ipywidgets.interact, w.observe, and w.on_click on Buttons.

A test that I did:

import time
import ipywidgets as widgets
from IPython.display import display

w = widgets.Text(disabled=False)
display(w)

while True:
    print(w.value)
    time.sleep(1)

I expect that when I enter something into the Text field, that it will output that text, but instead it continues printing out what it started with. There are no errors. So, for the above example, regardless of what I input into the resultant Text field, all that is printed is empty lines.


回答1:


This code doesn't work as intended in a normal notebook server, so probably won't work in Azure either. I suspect you need a thread process to read from the updated widget. Try this and see if you get anything printing in Azure Notebooks as you change the text field.

    import time
    import ipywidgets as widgets
    from IPython.display import display

    w = widgets.Text(disabled=False)
    display(w)

    def print_text(widget):
        print(widget['new'])

    w.observe(print_text, names='value')



回答2:


The problem is that communication between widgets and the Python kernel is asynchronous and confusing.

time.sleep(...) in the cell only blocks the Python interpreter and does not allow the widget Javascript implementation to send the changed value to the Python kernel (because the Python kernel is blocked and not doing anything).

If you create the widget and then modify the widget text entry and then evaluate w.value in the next cell interactively you will see the changed value.

See further discussion here (look for "async"):

https://github.com/AaronWatters/jp_proxy_widget/blob/master/notebooks/Tutorial.ipynb

In general if you want to force the Python interpreter to see some value sent from the Javascript widget implementation the Javascript side must call back to the Python interpreter in some way and the Python interpreter cannot be blocked by sleep or any other such mechanism.



来源:https://stackoverflow.com/questions/56403663/ipywidgets-widgets-values-not-changing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!