问题
I am using ipywidgets.widgets.Checkbox. Is there any way to handle the checkbox events? Please do help. I am a beginner.
edit: How to create a list of checkboxes?
回答1:
There aren't any direct events but you can use the observe
event. That will likely create more events than you want so you may want to filter them down to one.
from IPython.display import display
from ipywidgets import Checkbox
box = Checkbox(False, description='checker')
display(box)
def changed(b):
print(b)
box.observe(changed)
To create a "list" of widgets you can use container widgets. From the link:
from ipywidgets import Button, HBox, VBox
words = ['correct', 'horse', 'battery', 'staple']
items = [Button(description=w) for w in words]
left_box = VBox([items[0], items[1]])
right_box = VBox([items[2], items[3]])
HBox([left_box, right_box])
回答2:
Building on Jacques' answer: If using Jupyter Lab, rather than a standard Jupyter Notebook, you must also create an output widget and tell the callback function to write to it using a decorator. So the given example becomes:
import ipywidgets as widgets
box = widgets.Checkbox(False, description='checker')
out = widgets.Output()
@out.capture()
def changed(b):
print(b)
box.observe(changed)
display(box)
display(out)
These steps are documented here, but it is obvious that they are required when using Jupyter Lab.
来源:https://stackoverflow.com/questions/44667052/python-ipywidgets-checkbox-events