为什么我的 ipywidget observe 在一次状态更改时被多次调用?

Why is my ipywidget observe being call multiple times on a single state change?

我在 Jupyter notebook 的单元格中有一些代码同时使用了单选按钮和滑块。我有一个方法,我只想在选择更改时调用(在单选按钮的情况下);并且仅当滑块被释放时(在滑块的情况下)。

但是,使用 'observe' 方法会在单选按钮仅更改一次时触发多次(我相信它会触发 3 次)。当发生鼠标按下和鼠标弹起时,滑块观察方法会触发。

是否可以将其更改为仅调用一次,或者我需要使用 observe 以外的其他方法?

[编辑] 这是使用单选按钮的更新示例以及选择一次选项时打印的输出:

import ipywidgets as widgets

    def radio_called(sender):
        print('radio_called')
        print(sender)

    radio = widgets.RadioButtons(options=['option 1', 'option2', 'option3'])
    radio.observe(radio_called)
    display(radio)

单击一次选项时的打印输出: radio_called

{'name': '_property_lock', 'old': traitlets.Undefined, 'new': {'index': 1}, 'owner': RadioButtons(options=('option 1', 'option2', 'option3'), value='option 1'), 'type': 'change'}
radio_called
{'name': 'label', 'old': 'option 1', 'new': 'option2', 'owner': RadioButtons(index=1, options=('option 1', 'option2', 'option3'), value='option 1'), 'type': 'change'}
radio_called
{'name': 'value', 'old': 'option 1', 'new': 'option2', 'owner': RadioButtons(index=1, options=('option 1', 'option2', 'option3'), value='option2'), 'type': 'change'}
radio_called
{'name': 'index', 'old': 0, 'new': 1, 'owner': RadioButtons(index=1, options=('option 1', 'option2', 'option3'), value='option2'), 'type': 'change'}
radio_called
{'name': '_property_lock', 'old': {'index': 1}, 'new': {}, 'owner': RadioButtons(index=1, options=('option 1', 'option2', 'option3'), value='option2'), 'type': 'change'}

如果打印 sender 对象,您可以看到传递给函数的内容。每个实例都是一个不同的 Trait 变化(当你点击时不仅仅是一个单一的动作发生),试试下面的代码。

如果您希望过滤仅发生一次,请在您的 observe 调用中指定您想要的名称。例如

radio_input.observe(bind_selected_to_output, names=['value'])

    import ipywidgets as widgets # If not already imported

    output_radio_selected = widgets.Text() # Used to take the user input and access it when needed
    radio_input = widgets.RadioButtons(options=['Option 1', 'Option 2']) # Declare the set of radio buttons and provide options

    def bind_selected_to_output(sender): # Connect the input from the user to the output so we can access it
        print(sender)
        global selected_option # Global variable to hold the user input for reuse in your code
        output_radio_selected.value = radio_input.value
        selected_option = output_radio_selected.value # Example variable assigned the selected value
        print('Selected option set to: ' + selected_option) # For test purposes

    radio_input.observe(bind_selected_to_output, names=['value']) # Run the bind... function when the radio button is changed
    radio_input # Display the radio buttons to the user

查看此处了解更多信息:https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html#Traitlet-events