HBox中安排的SelectMultiple小部件的交互功能

时间:2019-08-07 17:27:04

标签: python-3.x jupyter interactive ipywidgets

我想用Jupyter笔记本构建一个交互式应用程序,但是我对小部件的使用还不多。

在我的代码中,我定义了2个SelectMultiple小部件(请参见下面的代码中的定义)。

我使用“ HBox”(请参见代码)将2个小部件组合在特定布局中。

我还定义了一个函数,该函数基于数据库中这两个小部件搜索的值,并返回一个等于数据库中所选元素数量的整数(请参见下面的代码)。

我想打印函数“ No_selected”的输出,以便当我在HBox布局中显示的2个SelectMultiple小部件中选择一个不同的输入时,它的输出交互地改变。

我尝试阅读小部件(https://ipywidgets.readthedocs.io/en/stable/user_guide.html)的文档。

我试图在函数之前使用Interact装饰器'@ Interact',但是当我这样做时,Jupyter为W1和W2显示了两个额外的小部件,而不是允许我通过使用HBox中的两个小部件来运行该函数。 / p>

W1(与W2类似)的小部件定义示例:

W1 = widgets.SelectMultiple(
    options=['Apples', 'Oranges', 'Pears'],
    value=['Oranges'],
    #rows=10,
    description='Fruits',
    disabled=False
)

布局示例:

Wboth = widgets.HBox([W1, W2])

函数定义示例:

def SELECTION(W1=('Apples'), W2=('Apples')):
    ...
    ...
    ...
    return No_selected

您能建议我该怎么做吗?

1 个答案:

答案 0 :(得分:1)

我认为您需要比标准interact多一些的东西,因为您不仅需要从正在更改的小部件中获取信息,而且还需要获取更多信息。

我整理了您想要的行为的class版本,发现使用observe比使用interact的次数要多得多,现在我对组合和子类化更加熟悉。您可以更改_observed_function来执行当前小部件选择所需的操作。

import ipywidgets as widgets

class SelectMultipleInteract(widgets.HBox):

    def __init__(self):
        self.W1 = widgets.SelectMultiple(
            options=['Apples', 'Oranges', 'Pears'],
            value=['Oranges'],
            #rows=10,
            description='Fruits',
            disabled=False
        )

        self.W2 = widgets.SelectMultiple(
            options=['Carrots', 'Potatoes', 'Tomatoes'],
            value=['Carrots'],
            #rows=10,
            description='Veg',
            disabled=False
        )

        self.selectors = [self.W1, self.W2]
        super().__init__(children=self.selectors)
        self._set_observes()

    def _set_observes(self):
        for widg in self.selectors:
            widg.observe(self._observed_function, names='value')

    def _observed_function(self, widg):
        for widg in self.selectors:
            print(widg.description)
            print(widg.get_interact_value())

SelectMultipleInteract()

enter image description here