Reputation: 391
In below code I created 2 tabs with a text box and a button in inside each tab. I want to select button one
and link an event for it. How can I do it?
import ipywidgets as widgets
lst = ['one', 'two']
list_widgets = [
widgets.HBox([widgets.Text(
placeholder="name",
description=name,
disabled=False),
widgets.Button(
description="ok")]) for name in lst]
children=list_widgets
tab = widgets.Tab(children)
[tab.set_title(num, name) for num, name in enumerate(lst)]
display(tab)
Upvotes: 1
Views: 1695
Reputation: 3219
To link an action to an ipywidget button you use the on_click
method for a button you have created. From ipywidget:
The Button is not used to represent a data type. Instead the button widget is used to handle mouse clicks. The on_click method of the Button can be used to register function to be called when the button is clicked.
But, if you create your layout using your strategy you'll be somewhat limited with your buttons because they'll have the same action (the same button will be referenced). In this example button
is used on both tabs:
import ipywidgets as widgets
def click(h):
print('button click')
button = widgets.Button(description="ok")
button.on_click(click)
lst = ['one', 'two']
list_widgets = [
widgets.HBox([widgets.Text(
placeholder="name",
description=name,
disabled=False),
button]) for name in lst]
children=list_widgets
tab = widgets.Tab(children)
[tab.set_title(num, name) for num, name in enumerate(lst)]
display(tab)
With some modifications you can add two buttons with different actions:
import ipywidgets as widgets
def click1(h):
print('button one click')
def click2(h):
print('button two click')
one = widgets.Button(description="ok")
one.on_click(click1)
two = widgets.Button(description="ok")
two.on_click(click2)
btn = [one, two]
lst = ["one", "two"]
list_widgets = [
widgets.HBox([widgets.Text(
placeholder="name",
description=name,
disabled=False),
btn[num]]) for num, name in enumerate(lst)]
children=list_widgets
tab = widgets.Tab(children)
[tab.set_title(num,name) for num, name in enumerate(lst)]
display(tab)
Upvotes: 2