【问题标题】:ipywidgets dropdown widgets: what is the onchange event?ipywidgets 下拉小部件:什么是 onchange 事件?
【发布时间】:2015-12-01 12:45:39
【问题描述】:

我可以在 ipython 笔记本小部件中为 button.on_click 注册一个处理程序,但我不知道如何为下拉小部件做同样的事情

import ipywidgets as widgets
from IPython.display import display

def on_button_clicked(b):
    print("Button clicked.")

button = widgets.Button(description="Click Me!")
display(button)

button.on_click(on_button_clicked)

但是对于

choose_task = widgets.Dropdown(
    options=['Addition', 'Multiplication', 'Subtraction'],
    value='Addition',
    description='Task:',
)

好像只有一个

on_trait_change(...)

如果我用这个注册一个处理程序,我可以用它来访问小部件的值吗? 我已经看到了处理程序的示例,并且小部件属于子类,并且处理程序可以使用 self 进行自省。但是如果我不想使用子类,处理程序如何知道事件的目标是哪个小部件?

【问题讨论】:

  • 你有想过你的内省问题吗?

标签: jupyter-notebook ipython


【解决方案1】:

this linkthe traitlet docs on github 之间玩玩,我终于想通了:

w = widgets.Dropdown(
    options=['Addition', 'Multiplication', 'Subtraction', 'Division'],
    value='Addition',
    description='Task:',
)

def on_change(change):
    if change['type'] == 'change' and change['name'] == 'value':
        print("changed to %s" % change['new'])

w.observe(on_change)

display(w)

总体而言,这看起来比不推荐使用的接口丰富得多,但它肯定可以使用更多示例。

【讨论】:

【解决方案2】:

您可以在observe 中指定更改名称。这使得代码更简洁,并且不会为您不需要的更改调用处理程序:

from IPython.display import display
from ipywidgets import Dropdown

def dropdown_eventhandler(change):
    print(change.new)

option_list = (1, 2, 3)
dropdown = Dropdown(description="Choose one:", options=option_list)
dropdown.observe(dropdown_eventhandler, names='value')
display(dropdown)

【讨论】:

  • 知道如何在选择一个值后使小部件消失/变为非活动状态吗?
  • 我实际上是在寻找一个带有两个按钮的小部件。点击一个动作A,点击另一个动作B。
  • @fabiob 在处理程序中尝试change.owner.disabled = True
【解决方案3】:

把它们放在一起

受先前答案和 lambda 表达式的启发,我使用了这个:

def function(option):
    print(option)


w = widgets.Dropdown(
    options=['None', 'Option 1', 'Option 2', 'Option 3'],
    description='Option:',
    disabled=False
)

w.observe(
    lambda c: plot_content(c['new']) if (c['type'] == 'change' and c['name'] == 'value') else None
)

display(w)

【讨论】:

  • 谢谢。我一直在寻找方法/示例来组合多个小部件来选择函数的值、切片/切块数据、从数据中选择绘图类型等。
  • 有什么解决办法吗? stackoverflow.com/questions/67927358/…
【解决方案4】:

我同意事件处理并不像期望的那样彻底:当您收到多个事件时,我一直在过滤事件,因为索引发生了典型的下拉更改,值发生了变化,即 change['name'] .

我正在做以下事情:

def on_dropdown_change(change):
    if change['name'] == 'value' and (change['new'] != change['old']):
        print('do something with the change')
dropdown =  ipywidgets.Dropdown({options=['one','two','three'],
                                 value='one'})
dropdown.observe(on_dropdown_change)

【讨论】:

【解决方案5】:

我相信这个想法是使用 trait name,例如价值。例如:

from ipywidgets import Dropdown

def handle_change():
    print type_sel.value

type_sel = Dropdown(description="Keypoint type", options=['surf', 'orb'])
type_sel.on_trait_change(handle_change, name="value")
display(type_sel)

SciPy 2015 Advanced Jupyter Video Tutorial

【讨论】:

  • 这是可怕的记录
  • 另外,当我尝试使用它时会收到警告:[...]/anaconda/lib/python2.7/site-packages/ipykernel/__main__.py:13: DeprecationWarning: on_trait_change is deprecated in traitlets 4.1: use observe instead 但是当我尝试使用observe 时,我的处理程序被调用了 3 次。
【解决方案6】:

我有同样的问题。这也引出了下一个问题,如何根据下拉菜单选择来连接按钮操作。

# Common Imports for Widgets
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets

'''
    Precusor:

    <class 'traitlets.utils.bunch.Bunch'>  It is a dictionary-like object containing:

    {'name': 'value', 'old': 'what_ever_the_old_value_was', 'new': 'what_ever_the_new_value_is', 
    'owner': Dropdown(description='the_user_defined_label:', index=1, # I'm not sure what this is
    options=()#list of options passed, 
    value='value_kwarg_value'), 'type': 'change'} # type: action_or_event type

    For more information see:

    https://traitlets.readthedocs.io/en/stable/using_traitlets.html#default-values-and-checking-type-and-value

    or

    https://github.com/jupyter-widgets/tutorial/blob/master/notebooks/08.00-Widget_Events.ipynb

    or a long but well done SciPy talk on the use of widgets @

    https://www.youtube.com/watch?v=HaSpqsKaRbo
'''

foo = ['a','b','c'] # List to use

# Function to apply to drop box object
def bar(x):
    '''
        I am intentionally passing what it is made of so you can see the output.
    '''
    print(x,'\n') # Whole object
    print(x.new,'\n') # New value


# Function for the button to select user input and do work
def get_user_selection(a): # A default arg is needed here, I am guessing to pass self
    # Displays the current value of dropbox1 and dropbox two
    display(dropbox1.value,dropbox2.value)


# creation of a widget dropdown object called dropbox1
dropbox1 = widgets.Dropdown(
    options=foo, # Object to iterate over
    description='Letter:', # User defined 
    value=foo[1], # Default value selection
    rows=len(foo), # The number of rows to display when showing the box
    interactive=True, # This makes the box interactive, I believe this is true by default
);

# Drop box of k,v like pairs 
dropbox2 = widgets.Dropdown(
    options=[('One', 1), ('Two', 2), ('Three', 3)],
    value=2,
    description='Number:',
)

# Button to click
select_button = widgets.Button(
    description='Click', # User defined
    disabled=False
)

# Event Handlers
dropbox1.observe(bar,names='value')
dropbox2.observe(bar,names='value')
select_button.on_click(get_user_selection)


# I you need more help with commands try things like:
# interact_manual?
# display(arg.keys,arg.traits)
# print(widgets.widget_type_here.widget_function_or_attr.__doc__)

# Create a UI object to display things.  There are other ways of organizing them.
ui = widgets.HBox([dropbox1,dropbox2,select_button]) # pass an array of widgets to the ui

# display the UI
display(ui)

点击几下后会显示以下内容。

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多