Python Ipywidgets: Passing Button (value/description) on click to a textarea widget

时间:2017-08-04 12:35:50

标签: python python-2.7 ipywidgets

I'm currently trying out ipywidgets in Jupyter. I wanted to pass the value or description that the button has to the textArea and append whichever button value it indicates.

So far this is the code that I have:

#testing adding button and textbox
from ipywidgets import widgets as wd
from ipywidgets import Layout, Box
from IPython.display import display

btnLayout = Layout(flex='1 1 auto', width='auto')

btns= [
    wd.Button(description="Add Route"),
    wd.Button(description="234"),
    wd.Button(description="411")
]

box_layout = Layout(display='flex',
                    flex_flow='row',
                    align_items='stretch')

box = Box(children=btns, layout=box_layout)

display(box)
box.children[1].layout.visibility = 'hidden'
box.children[2].layout.visibility = 'hidden'

txtArea = wd.Textarea()
display(txtArea)

def show(b):
    box.children[1].layout.visibility = 'visible'
    box.children[2].layout.visibility = 'visible'

#function intended to append button value/description to textArea
def add_text(b):
    txtArea.value = "test, " + txtArea.value

box.children[0].on_click(show)
box.children[1].on_click(add_text)
box.children[2].on_click(add_text)

I read about links and observe... but I don't think it will do what I intend to have in my code. Any ideas how to work around this if there is no direct way, unlike the intsliders etc.?

1 个答案:

答案 0 :(得分:0)

只是为了澄清Button中的ipywidgets类没有value属性,但您可以通过继承它来添加一个(see this gist for an example of that)。

如果我正确理解了这个问题,我认为这对你有用;

#testing adding button and textbox
from ipywidgets import widgets as wd
from ipywidgets import Layout, Box
from IPython.display import display

btnLayout = Layout(flex='1 1 auto', width='auto')

btns= [
    wd.Button(description="Add Route"),
    wd.Button(description="234"),
    wd.Button(description="411")
]

box_layout = Layout(display='flex',
                    flex_flow='row',
                    align_items='stretch')

box = Box(children=btns, layout=box_layout)

display(box)
box.children[1].layout.visibility = 'hidden'
box.children[2].layout.visibility = 'hidden'

txtArea = wd.Textarea()
display(txtArea)

def show(b):
    box.children[1].layout.visibility = 'visible'
    box.children[2].layout.visibility = 'visible'

#function intended to append button value/description to textArea
def add_text(b):
    txtArea.value = b.description + txtArea.value

box.children[0].on_click(show)
box.children[1].on_click(add_text)
box.children[2].on_click(add_text)

如果这对您不起作用,请在下面发表评论。