Overwrite string in for loop in Jupyter Lab Output widget

我只是一个虾纸丫 提交于 2021-01-28 06:47:39

问题


I am trying to create a sort of survey using Jupyter widgets. As a bare-bone example, I would like to ask the user if he likes a kind of fruit in a list, let him check yes/no in a RadioButtons widget, let him submit his answer, and then ask him if he likes the next fruit.

I would expect something like this:

Do you like apples?
* yes
* no
Submit

After pressing Submit, the apples string would be substituted by the next fruit in the list:

Do you like oranges?
* yes
* no
Submit

What I am getting instead is:

Do you like apples?
* yes
* no
Submit

And after pressing Submit:

Do you like apples?Do you like oranges?
* yes
* no
Submit

So, the survey question string is not overwritten, but appended to the previous string, even though I am clearing the Output widget with clear_output method.

This is what I have achieved so far:

import asyncio

from IPython.display import display, clear_output
import ipywidgets as widgets


def create_multipleChoice_widget(description_out, options):
    
    alternativ = widgets.RadioButtons(options=options,
                                      )
    check = widgets.Checkbox(description="Submit")
    
    return widgets.VBox([alternativ, check])


def wait_for_change(widget, value):
    future = asyncio.Future()
    def getvalue(change):
        # make the new value available
        future.set_result(change.new)
        widget.unobserve(getvalue, value)
    widget.observe(getvalue, value)
    return future


fruits = ["apple",
          "orange",
          "kiwi",
          ]


description_out = widgets.Output()
box = create_multipleChoice_widget(description_out, ["yes", "no"])
    


async def f():
    for fruit in fruits:
        
        description = f"Do you like {fruit}s?"
        description_out.append_stdout(description)
        
        alternativ = box.children[0]
        check = box.children[1]
        
        x = await wait_for_change(check, 'value')
        description_out.clear_output()
        #clear_output()
        
asyncio.ensure_future(f())

display(description_out)
display(box)

I am not very familiar with ipywidgets or asyncio. I managed to write this code after reading this and this. As you can see, for the answer submission, I am using a Check widget. I tried to use a Button widget instead (and it would be my preference), but I did not manage to make it work, since it has no value argument.

I appreciate any suggestion!

Configuration:

  • Jupyter Lab 3.0.5
  • ipywidgets 7.6.3
  • Python 3.7.9
  • Environment installed with Conda, using conda-forge channel, on Ubuntu 18.04

来源:https://stackoverflow.com/questions/65761354/overwrite-string-in-for-loop-in-jupyter-lab-output-widget

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