使用Ipython ipywidget创建变量?

时间:2016-02-12 11:06:15

标签: ipython jupyter-notebook ipywidgets

这看起来很简单但我找不到一个例子或者自己解决这个问题。如何使用ipywidget小部件创建或返回可在以下单元格中使用的python变量/对象(如列表或字符串)?

2 个答案:

答案 0 :(得分:12)

http://blog.dominodatalab.com/interactive-dashboards-in-jupyter/对ipywidgets进行了很好的介绍,回答了这个问题。

您需要两个小部件,一个用于输入,另一个用于绑定该输入的值。这是文本输入的示例:

from ipywidgets import widgets  

# Create text widget for output
output_variable = widgets.Text()

# Create text widget for input
input_text = widgets.Text()

# Define function to bind value of the input to the output variable 
def bind_input_to_output(sender):
    output_text.value = input_text.value

# Tell the text input widget to call bind_input_to_output() on submit
input_text.on_submit(bind_input_to_output)

# Display input text box widget for input
input_text

# Display output text box widget (will populate when value submitted in input)
output_text

# Display text value of string in output_text variable
output_text.value

# Define new string variable with value of output_text, do something to it
uppercase_string = output_text.value.upper()
print uppercase_string

然后,您可以在整个笔记本中使用uppercase_string或output_text.value字符串。

可以使用类似的模式来使用其他输入值,例如interact()滑块:

from ipywidgets import widgets, interact

# Create text widget for output
output_slider_variable = widgets.Text()

# Define function to bind value of the input to the output variable 
def f(x):
    output_slider_variable.value = str(x)

# Create input slider with default value = 10    
interact(f, x=10)

# Display output variable in text box
output_slider_variable

# Create and output new int variable with value of slider
new_variable = int(output_slider_variable.value)
print new_variable

# Do something with new variable, e.g. cube
new_variable_cubed = pow(new_variable, 3)
print new_variable_cubed

Screenshot of iPython notebook to illustrate binding variables from ipywidgets Text() and interact() for use throughout notebook

答案 1 :(得分:4)

另一种可能更容易的解决方案是使用interactive。它的行为与interact非常相似,但允许您在仅创建单个小部件时访问后续单元格中的返回值。

下面是一个简单的示例,更完整的文档是here

from ipywidgets import interactive
from IPython.display import display

# Define any function
def f(a, b):
    return a + b

# Create sliders using interactive
my_result = interactive(f, a=(1,5), b=(6,10))

# You can also view this in a notebook without using display.
display(my_result)

现在,您可以根据需要访问结果值以及窗口小部件的值。

my_result.result  # current value of returned object (in this case a+b)
my_result.children[0].value # current value of a
my_result.children[1].value # current value of b