Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ipywidgets checkbox events

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?

like image 932
Sudharsan Avatar asked Jul 16 '26 10:07

Sudharsan


2 Answers

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])
like image 126
Jacques Kvam Avatar answered Jul 19 '26 00:07

Jacques Kvam


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.

like image 44
Dustin Michels Avatar answered Jul 19 '26 00:07

Dustin Michels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!