How to define the default value of a Slider widget

2019-07-18 04:53发布

On a Jupyter Notebook and using ipywidgets I can create sliders using the compact version

import ipywidgets as ip
def f(x):
    print(x)
ip.interact(f, x = (0, 1, 1))

The slider's default value is 0 but I would like to make it 1. How can I do this?

2条回答
你好瞎i
2楼-- · 2019-07-18 05:38

Setting a default value in the function definition should work:

import ipywidgets as ip
def f(x=1):
    print(x)
ip.interact(f, x = (0, 1, 1))
查看更多
Bombasti
3楼-- · 2019-07-18 05:54

The widget abbreviations (using tuples to request sliders, etc.) only expose a small subset of the options that can be passed to a widget. Default values come from the default value in the function definition if available, or the center of the range if not. If you don't want to change the signature of your existing function to give it a default argument, you have two options to specify the initial value:

  1. Wrap your function in another one that specifies defaults:

    def f(x, y):
        print(x, y)
    
    @interact(x=(0, 5), y=(-1.,3.))
    def g(x=1, y=2.0):
        return f(x, y)
    
  2. instantiate a Widget directly and specify the value attribute, instead of relying on the abbreviations:

    w = widgets.IntSlider(value=1, min=0, max=1)
    interact(f, x=w)
    
查看更多
登录 后发表回答