如何让多个窗口小部件按钮在Jupyter Notebook中执行不同的操作?

时间:2019-09-06 01:20:55

标签: python jupyter-notebook jupyter ipywidgets

我正在尝试创建一系列按钮,这些按钮会根据某些情况从数据集中获取样本。我有一个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()以及如何连接它,以便单击按钮可以输出相应的样本摘要?

我希望单击按钮可以输出其示例摘要,如上所示。

2 个答案:

答案 0 :(得分:0)

将您的示例扩展为可以使用时,我没有任何问题 多个按钮。我不知道你在哪里困惑。

multiple button example

有时在小部件回调中发生的异常不会 被打印-也许您的代码中有一个错误,您无法 出于这个原因。最好拥有一切 包裹在“不包含:”

答案 1 :(得分:0)

使用列表创建了两个按钮。猜代码本身会更好地解释。

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)