创建后使用Button将HBox添加到VBox

时间:2019-08-27 20:13:42

标签: python ipywidgets

我正在尝试为我制作的模块制作输入小部件。

输入窗口小部件应在下方具有标题栏和可变数量的输入行。我想过要有一个添加按钮,它应该在标题行的正下方添加一行。

我尝试在github上关注此stackoverflow questionthis issue。但是这些建议只会在VBox的底部添加一个小部件。

我做了下面的虚拟例子。

import ipywidgets as w

def add_button_clicked(b):
    #This adds new line at bottom
    #input_box.children += (line(),)
    #This is intended to add line below title but does not work
    input_box.children = (input_box.children[0], line(), input_box.children[1:])

add = w.Button(icon="plus-circle")
add.on_click(add_button_clicked)

title = w.HBox([w.Label(value=str(i)) for i in range(3)]+[add])

def line():
    delete = w.Button(icon="trash")
    return w.HBox([w.FloatText(value=i) for i in range(3)]+[delete])

input_box = w.VBox([title,line()])
display(input_box)

但是,这不会产生预期的新行。 不幸的是,单击该按钮不会引发错误。

1 个答案:

答案 0 :(得分:1)

在您的示例中,您要为包含两个HBox对象和一个tuple的元组分配给input_box.children。您可以通过在add_button_clicked函数的开头添加一些“调试”行来进行检查:

print(type(input_box.children[0]))
print(type(line()))
print(type(input_box.children[1:]))

解决方案很容易,只需使用+连接元组:

input_box.children = (input_box.children[0], line()) + input_box.children[1:]