5

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?

Sudharsan
  • 53
  • 1
  • 1
  • 5

2 Answers2

13

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])
Jacques Kvam
  • 2,856
  • 1
  • 26
  • 31
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.

Dustin Michels
  • 2,951
  • 2
  • 19
  • 31