ipywidgets下拉小部件:onchange事件是什么?

时间:2015-12-01 12:45:40

标签: ipython ipython-notebook

我可以在ipython notebook小部件中为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来内省。但是如果我不想使用子类,那么处理程序如何知道哪个小部件是事件的目标。?

6 个答案:

答案 0 :(得分:23)

this linkthe traitlet docs on github之间,只是玩弄,我终于明白了:

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, NULL);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, offsetof(Vertex, r), NULL);
glDrawArrays(GL_TRIANGLES, 0, vertex_amount);
glBindBuffer(GL_ARRAY_BUFFER, 0);

总体而言,这看起来比不赞成使用的界面更丰富,但它绝对可以使用更多示例。

答案 1 :(得分:1)

我认为这个想法是使用特征名称,例如值。例如:

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

答案 2 :(得分:1)

全部放在一起

灵感来自之前的答案和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)

答案 3 :(得分:1)

我同意事件处理并不像期望的那样彻底:我已经过滤了事件,因为当索引发生变化时,您会收到典型下拉列表更改的多个事件,值会发生变化,即更改['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)

答案 4 :(得分:0)

您可以在observe中指定更改名称。这样可以使代码更简洁,并且只为正确的更改名称调用处理程序:

from IPython.display import display
from ipywidgets import Dropdown

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

file_list = (1, 2, 3)
file_dropdown = Dropdown(description="File name:", options=file_list)
file_dropdown.observe(file_dropdown_eventhandler, names='value')
display(file_dropdown)

答案 5 :(得分:0)

我有同样的问题。这也引出了下一个问题,即如何基于下拉菜单选择来对按钮操作进行接口。

# 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)

单击几次后,将显示以下内容。

Code output that has been run.

相关问题