首页 > 解决方案 > 创建后使用 Button 将 HBox 添加到 VBox

问题描述

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

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

我试过在 github 上关注这个stackoverflow 问题这个问题。但是这些建议只是在 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)

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

标签: pythonipywidgets

解决方案


在您的示例中,您正在分配一个包含两个HBox对象和一个对象tuple的元组input_box.childrenadd_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:]

推荐阅读