ipywidgets下拉小部件:什么是onchange事件? [英] ipywidgets dropdown widgets: what is the onchange event?

查看:94
本文介绍了ipywidgets下拉小部件:什么是onchange事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在ipython笔记本小部件中为button.on_click注册一个处理程序,但是我不知道如何对下拉小部件执行相同的操作

I can register a handler to button.on_click in ipython notebook widgets, but I don't know how to do the same for a dropdown widget

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进行内省.但是,如果我不想使用子类,那么处理程序如何知道事件的目标是哪个小部件??

if I register a handler with this, can I use it to access the value of the widget? I have seen examples with the handler and the widget belong to a subclass, and the handler can use self to introspect. But if I don't want to use a subclass, how does the handler know what widget was the target of the event.?

推荐答案

github上的traitlet文档只是在玩耍,我终于弄明白了:

Between this link and the traitlet docs on github and just playing around, I finally figured this out:

w = widgets.Dropdown(
    options=['Addition', 'Multiplication', 'Subtraction'],
    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)

总的来说,这看起来比不推荐使用的界面要丰富得多,但是肯定可以使用更多示例.

Overall this looks a lot richer than the deprecated interface, but it could definitely use more examples.

这篇关于ipywidgets下拉小部件:什么是onchange事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆