How to tell `ipywidgets.interactive`, that it should consider only specific parameters as widgets?

99封情书 提交于 2021-01-28 09:19:03

问题


It seems like ipywidgets.interactive tries to make every imput after the function to be a widget. In the following example, I get two widgets, one for age and one for name:

import ipywidgets 

def greetings(age, name='John'):
    print(f'{name} is {age} years old')

ipywidgets.interactive(greetings, age = widgets.IntSlider(), name = "Bob")

My expectation was, that I only get one widget for age, since it is of type ipywidgets.widgets.widget_int.IntSlider whereas "Bob" is of type str (where I don't see the link to widgets). The automated widget creation causes two problems: 1. I don't want that the user can specify every parameter 2. Some parameters like tuples (not shown in the example) will result in an error.

How to tell ipywidgets.interactive, that it should consider only specific parameters as widgets?

help(ipywidgets.interactive) and the documentation were not helpful.


回答1:


Firstly, thanks for the clear example and description.

You can leverage the fixed function in ipywidgets to pass fixed kwargs of any type through your interactive call, but without generating widgets for them. See below:

import ipywidgets 

def greetings(age, name='John'):
    print(f'{name} is {age} years old')

ipywidgets.interactive(greetings, 
                       age = ipywidgets.IntSlider(), 
                       name = ipywidgets.fixed("Bob")
                      )

You should also be able to pass tuples through this method. See more information in the documentation: https://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html#Fixing-arguments-using-fixed



来源:https://stackoverflow.com/questions/60152014/how-to-tell-ipywidgets-interactive-that-it-should-consider-only-specific-para

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!