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

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

问题描述

我可以在 ipython notebook 小部件中为 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', '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)

总的来说,这看起来比已弃用的界面丰富得多,但它肯定可以使用更多示例.

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

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

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