Create slider-with-buttons widget

22 views
Skip to first unread message

Alexander Plavin

unread,
Aug 9, 2016, 6:48:26 AM8/9/16
to Project Jupyter

Often I use sliders from ipywidgets both for numeric data (IntSlider) and for selection (SelectionSlider). When I need to go over several consequent slider values it is convenient to have buttons like next/prev step, and as ipywidgets doesn't provide anything like this I implemented it myself:

import ipywidgets as iw

slider = iw.SelectionSlider(options=['a', 'b', 'c', 'd', 'e'])

btn_prev = iw.Button(description='<')
btn_prev.layout.width = '32px'
@btn_prev.on_click
def _(*_):
    ind = slider.options.index(slider.value)
    if ind > 0:
        slider.value = slider.options[ind - 1]

btn_next = iw.Button(description='>')
btn_next.layout.width = '32px'
@btn_next.on_click
def _(*_):
    ind = slider.options.index(slider.value)
    if ind < len(slider.options) - 1:
        slider.value = slider.options[ind + 1]

def upd_btns_state(*_):
    btn_prev.disabled = slider.value == slider.options[0]
    btn_next.disabled = slider.value == slider.options[-1]
slider.observe(upd_btns_state, 'value')
upd_btns_state()

display(iw.HBox(children=[btn_prev, slider, btn_next]))

This basically works (not for dict as options through, but that's not difficult to add), but I have to paste this code everywhere I need a slider, and can't use it with interact.

What I think I need is make a widget which contains all this stuff and exposes only value, like a plain SelectionSlider. However, I couldn't find any docs about how to implement this anywhere (documentation on creating custom widgets addresses only making a widget from scratch, including html/javascript code) - any ideas?

Reply all
Reply to author
Forward
0 new messages