如何让多个小部件按钮在 Jupyter Notebook 中执行不同的操作?
How to have multiple widget buttons perform different actions in Jupyter Notebook?
我正在尝试制作一系列按钮,这些按钮根据某些场景从数据集中获取样本。我有一组 3x2 的按钮,每个按钮描述不同的场景。我似乎无法让他们执行各自的操作。
我想我了解如何将单击按钮的操作与其响应联系起来。但是,我不明白如何对多个按钮执行相同的操作。
这是我的代码,它使单个独立按钮起作用:
button = widgets.Button(description='Generate message!')
out = widgets.Output()
def on_button_clicked(_):
samp_text = raw_data.sample(1).column(1)
# "linking function with output"
with out:
# what happens when we press the button
print(samp_text)
# linking button and function together using a button's method
button.on_click(on_button_clicked)
# displaying button and its output together
widgets.VBox([button,out])
现在我要做的是在不同情况下采取不同类型的样本。所以我为每种类型的采样方法编写了函数,returns table 的比例:
1 47.739362
2 44.680851
3 4.920213
9 2.659574
Name: vote, dtype: float64
但是,第一个示例中的相同方法只有一个按钮,但在多个按钮上效果不一样。如何使用 widgets.Output() 以及如何连接它以便单击按钮输出相应的示例摘要?
我希望点击的按钮输出其示例摘要,如上所示。
我扩展你的例子没有任何问题
多个按钮。不知道你哪里糊涂了
有时小部件回调中发生的异常不会
得到打印——也许你的代码中有一个你无法解决的错误
看到这个原因。最好拥有一切
包裹在 "with out:"
使用列表创建了两个按钮。猜测代码本身解释得更好。
from ipywidgets import Button, HBox
thisandthat = ['ON', 'OFF']
switch = [Button(description=name) for name in thisandthat]
combined = HBox([items for items in switch])
def upon_clicked(btn):
print(f'The circuit is {btn.description}.', end='\x1b\r')
for n in range(len(thisandthat)):
switch[n].style.button_color = 'gray'
btn.style.button_color = 'pink'
for n in range(len(thisandthat)):
switch[n].on_click(upon_clicked)
display(combined)
我正在尝试制作一系列按钮,这些按钮根据某些场景从数据集中获取样本。我有一组 3x2 的按钮,每个按钮描述不同的场景。我似乎无法让他们执行各自的操作。
我想我了解如何将单击按钮的操作与其响应联系起来。但是,我不明白如何对多个按钮执行相同的操作。
这是我的代码,它使单个独立按钮起作用:
button = widgets.Button(description='Generate message!')
out = widgets.Output()
def on_button_clicked(_):
samp_text = raw_data.sample(1).column(1)
# "linking function with output"
with out:
# what happens when we press the button
print(samp_text)
# linking button and function together using a button's method
button.on_click(on_button_clicked)
# displaying button and its output together
widgets.VBox([button,out])
现在我要做的是在不同情况下采取不同类型的样本。所以我为每种类型的采样方法编写了函数,returns table 的比例:
1 47.739362
2 44.680851
3 4.920213
9 2.659574
Name: vote, dtype: float64
但是,第一个示例中的相同方法只有一个按钮,但在多个按钮上效果不一样。如何使用 widgets.Output() 以及如何连接它以便单击按钮输出相应的示例摘要?
我希望点击的按钮输出其示例摘要,如上所示。
我扩展你的例子没有任何问题 多个按钮。不知道你哪里糊涂了
有时小部件回调中发生的异常不会 得到打印——也许你的代码中有一个你无法解决的错误 看到这个原因。最好拥有一切 包裹在 "with out:"
使用列表创建了两个按钮。猜测代码本身解释得更好。
from ipywidgets import Button, HBox
thisandthat = ['ON', 'OFF']
switch = [Button(description=name) for name in thisandthat]
combined = HBox([items for items in switch])
def upon_clicked(btn):
print(f'The circuit is {btn.description}.', end='\x1b\r')
for n in range(len(thisandthat)):
switch[n].style.button_color = 'gray'
btn.style.button_color = 'pink'
for n in range(len(thisandthat)):
switch[n].on_click(upon_clicked)
display(combined)