2016-02-12 84 views
2

這看起來很簡單,但我一直無法找到一個例子或自己解決這個問題。如何使用ipywidget小部件來創建或返回可用於下一個單元格的python變量/對象,如列表或字符串?使用Ipython ipywidget創建變量?

回答

5

有一個很好的介紹ipywidgets在http://blog.dominodatalab.com/interactive-dashboards-in-jupyter/這回答了這個問題。

您需要兩個小部件,一個用於輸入,另一個用於綁定該輸入的值。下面是文字輸入的例子:

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字符串,例如,在整個筆記本電腦。

可以使用類似的模式來使用其他輸入值,例如,的相互作用()滑塊:

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

在示例中是否存在拼寫錯誤?應該是:'output_text = widgets.Text()'Not:'output_variable = widgets.Text()' – hmelberg

0

另一種解決方案,其可以更容易是使用interactive。它的行爲很像0​​,但允許您訪問稍後單元格中的返回值,同時只創建一個小部件。

一個簡單的例子如下,更完整的文檔是here - 滾動大約一半的interactive例子。

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