Python ipywidgets checkbox events

佐手、 提交于 2020-01-02 15:54:38

问题


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

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