首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Ipython ipywidget创建变量?

使用Ipython ipywidget创建变量?
EN

Stack Overflow用户
提问于 2016-02-12 19:06:15
回答 2查看 26.6K关注 0票数 22

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-29 20:32:41

http://blog.dominodatalab.com/interactive-dashboards-in-jupyter/上有一个很好的关于ipywidgets的介绍,它回答了这个问题。

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

代码语言:javascript
复制
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()滑块:

代码语言:javascript
复制
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

票数 22
EN

Stack Overflow用户

发布于 2017-08-22 05:13:21

另一种可能更简单的解决方案是使用interactive。它的行为很像interact,但允许您访问后面的单元格中的返回值,而只创建一个小部件。

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

代码语言:javascript
复制
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)

现在,您可以访问结果值,如果需要,还可以访问小部件的值。

代码语言:javascript
复制
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
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35361038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档