创建后使用Button将HBox添加到VBox
Add HBox to VBox using Button after creation
我正在尝试为我制作的模块制作一个输入小部件。
输入小部件应该有一个标题栏和下面可变数量的输入行。我想有一个添加按钮,它应该在标题行的正下方添加一行。
我已尝试在 github 上关注此 Whosebug question and this 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)
然而,这并没有像预期的那样产生一个新行。
不幸的是,点击按钮不会引发错误。
在您的示例中,您将一个包含两个 HBox
对象和一个 tuple
对象的元组分配给 input_box.children
。您可以通过在 add_button_clicked
函数的开头添加一些 "debug" 行来检查这一点:
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:]
我正在尝试为我制作的模块制作一个输入小部件。
输入小部件应该有一个标题栏和下面可变数量的输入行。我想有一个添加按钮,它应该在标题行的正下方添加一行。
我已尝试在 github 上关注此 Whosebug question and this 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)
然而,这并没有像预期的那样产生一个新行。 不幸的是,点击按钮不会引发错误。
在您的示例中,您将一个包含两个 HBox
对象和一个 tuple
对象的元组分配给 input_box.children
。您可以通过在 add_button_clicked
函数的开头添加一些 "debug" 行来检查这一点:
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:]