【问题标题】:How to have multiple widget buttons perform different actions in Jupyter Notebook?如何让多个小部件按钮在 Jupyter Notebook 中执行不同的操作?
【发布时间】:2019-09-06 01:20:55
【问题描述】:

我正在尝试制作一系列按钮,这些按钮根据某些场景从数据集中获取样本。我有一组 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() 以及如何连接它以便单击按钮输出相应的示例摘要?

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

【问题讨论】:

    标签: python jupyter-notebook jupyter ipywidgets


    【解决方案1】:

    我没有任何问题扩展你的例子来使用 多个按钮。不知道你在哪里搞糊涂了。

    有时小部件回调中发生的异常不会 被打印出来——也许你的代码中有一个你不能解决的错误 看到这个原因。最好拥有一切 包裹在“with out:”中

    【讨论】:

      【解决方案2】:

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

      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)
      
      

      【讨论】:

        猜你喜欢
        • 2012-06-05
        • 2018-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-18
        • 1970-01-01
        • 2015-08-04
        • 1970-01-01
        相关资源
        最近更新 更多