问题
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