Add HBox to VBox using Button after creation

北城余情 提交于 2019-12-13 03:15:04

问题


I am trying to make an input widget for a module i have made.

The input widget should have a title bar and a variable number of input lines below. I had in mind to have an add button which should add a line directly below the title line.

I have tried following this stackoverflow question and this issue on github. But these suggestions only add a widget to the bottom of the VBox.

I have made the following dummy example.

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)

However this does not produce a new line as expected. Unfortunately clicking the button does not throw an error.


回答1:


In your example you are assigning a tuple containing two HBox objects and one tuple to input_box.children. You can check this by adding some "debug" lines at the start of add_button_clicked function:

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

Solution is easy, just concatenate tuples using +:

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


来源:https://stackoverflow.com/questions/57681671/add-hbox-to-vbox-using-button-after-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!