ipython的变量_使用Ipython ipywidget创建变量?

This seems really simple but I have not been able to find a single example or to solve this myself. How do I use an ipywidget widget to create or return a python variable/object, such as a list or string, that can be used in a following cell?

解决方案

There is a good introduction to ipywidgets at http://blog.dominodatalab.com/interactive-dashboards-in-jupyter/ which answers this question.

You need two widgets, one for input, and another to bind the value of that input. Here's an example for text input:

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

You can then use the uppercase_string, or output_text.value string, for example, throughout your notebook.

A similar pattern can be followed for using other input values, e.g. the interact() slider:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值