这看起来真的很简单,但我还没有找到一个例子,也没有自己解决这个问题。如何使用ipywidget小部件创建或返回可在下面的单元格中使用的python变量/对象,如列表或字符串?
发布于 2016-02-29 20:32:41
在http://blog.dominodatalab.com/interactive-dashboards-in-jupyter/上有一个很好的关于ipywidgets的介绍,它回答了这个问题。
您需要两个小部件,一个用于输入,另一个用于绑定输入的值。下面是一个文本输入的例子:
from ipywidgets import widgets
# Create text widget for output
output_text = 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

发布于 2017-08-22 05:13:21
另一种可能更简单的解决方案是使用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 bhttps://stackoverflow.com/questions/35361038
复制相似问题