我正在尝试制作一系列按钮,这些按钮根据某些场景从数据集中获取样本。我有一组 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 methodbutton.on_click(on_button_clicked)# displaying button and its output togetherwidgets.VBox([button,out])现在我要做的是在不同的情况下采取不同类型的样本。因此,我为每种返回比例表的采样方法编写了函数:1 47.7393622 44.6808513 4.9202139 2.659574Name: vote, dtype: float64但是,第一个示例中只有一个按钮的相同方法不适用于多个按钮。如何使用 widgets.Output() 以及如何连接它以便单击按钮输出相应的示例摘要?我希望单击的按钮能够输出其示例摘要,如上所示。
2 回答

凤凰求蛊
TA贡献1825条经验 获得超4个赞
扩展您的示例以使用多个按钮我没有任何问题。我不知道你在哪里困惑。
有时,小部件回调中发生的异常不会被打印出来——也许您的代码中有一个错误,因此您看不到。最好将所有内容都包裹在“with out:”中

尚方宝剑之说
TA贡献1788条经验 获得超4个赞
使用列表创建了两个按钮。猜测代码本身解释得更好。
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)
添加回答
举报
0/150
提交
取消