Issue
I want to create a list of checkboxes so users can select from a list of data. I've created checkboxes for each piece of data and I'd now like the ticking of these checkboxes to add data to a list.
import ipywidgets as widgets
data = ["data1", "data2", "data3", "data4"]
selected_data = []
checkboxes = [widgets.Checkbox(value=False, description=label) for label in data]
widgets.VBox(children=checkboxes)
I'd like to do something along the lines of
def add_to_selected(d):
selected_data.append(d)
checkboxes[0].observe(add_to_selected)
Where this would add a value to the selected_data
list. I don't know how to get the checkboxes in the VBox to behave like this.
Solution
I've found a solution that works but I feel is quite hacky. I'd appreciate it if anyone has any suggestions on a way to simplify it.
This solutions allows the creation of a checkbox for each key in the data
dictionary. On clicking the checkbox the selected key is added to the selected_data
list.
import ipywidgets as widgets
data = {"label_1":"data_1", "label_2":"data_2", "label_3":"data_3"}
names = []
checkbox_objects = []
for key in data:
checkbox_objects.append(widgets.Checkbox(value=False, description=key))
names.append(key)
arg_dict = {names[i]: checkbox for i, checkbox in enumerate(checkbox_objects)}
ui = widgets.VBox(children=checkbox_objects)
selected_data = []
def select_data(**kwargs):
selected_data.clear()
for key in kwargs:
if kwargs[key] is True:
selected_data.append(key)
print(selected_data)
out = widgets.interactive_output(select_data, arg_dict)
display(ui, out)
Answered By - Gar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.