如何让多个小部件按钮在 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])

现在我要做的是在不同的情况下采取不同类型的样本。因此,我为每种返回比例表的采样方法编写了函数:


1    47.739362

2    44.680851

3     4.920213

9     2.659574

Name: vote, dtype: float64

但是,第一个示例中只有一个按钮的相同方法不适用于多个按钮。如何使用 widgets.Output() 以及如何连接它以便单击按钮输出相应的示例摘要?


我希望单击的按钮能够输出其示例摘要,如上所示。


慕村225694
浏览 148回答 2
2回答

凤凰求蛊

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

尚方宝剑之说

使用列表创建了两个按钮。猜测代码本身解释得更好。from ipywidgets import Button, HBoxthisandthat = ['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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python