Python Ipywidgets:点击文本区域小部件时传递按钮 (value/description)

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

我目前正在 Jupyter 中试用 ipywidgets。我想将按钮具有的值或描述传递给 textArea 并附加它指示的任何按钮值。

到目前为止,这是我拥有的代码:

#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)

我阅读了有关链接的信息并进行了观察...但我认为它不会执行我打算在我的代码中包含的内容。如果没有直接的方法,与 intsliders 等不同,有什么想法可以解决这个问题吗?

澄清一下 ipywidgets 中的 Button class 没有 value 属性,但您可以通过子class 添加一个属性( 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)

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