问题
I am trying to make VBox widget and and add a new row with text when button is clicked.
I try the following code
import ipywidgets as wg
from ipywidgets import Layout
from IPython.display import display
vb = wg.VBox([wg.Text('1'),wg.Text('2')])
btn = wg.Button(description = 'Add')
def on_bttn_clicked(b):
vb.children=tuple(list(vb.children).append(wg.Text('3')))
btn.on_click(on_bttn_clicked)
display(vb, btn)
list(hb.children)
But the assignment "hb.children=" does not work... Is there a way to edit container widgets with code in the same cell?
回答1:
You can use a simple plus to concatenate two lists.
vb.children=tuple(list(vb.children) + [new_button])
So your full script will look like this:
import ipywidgets as wg
from ipywidgets import Layout
from IPython.display import display
vb = wg.VBox([wg.Text('1'),wg.Text('2')])
btn = wg.Button(description = 'Add')
def on_bttn_clicked(b):
vb.children=tuple(list(vb.children) + [wg.Text('3')])
btn.on_click(on_bttn_clicked)
display(vb, btn)
list(vb.children)
来源:https://stackoverflow.com/questions/44986451/how-to-add-widgets-to-container-widget-in-ipython-jupyter