3

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?

  • What do you mean by "does not work"? – Bonifacio2 Jul 08 '17 at 13:07
  • The line `vb.children=tuple(list(vb.children).append(wg.Text('3'))` may be where your main problem is: `list(vb.children).append(wg.Text('3')` return `None` and therefore you are passing `None` to the `tuple` constructor method. This should, in fact, throw an error. Please share that error here. – Abdou Jul 08 '17 at 13:56
  • 1
    Yes @Abdou you are right. append method return None. I modified the code `def on_bttn_clicked(b): temp = list(vb.children) temp.append(wg.Text('3')) vb.children=temp` It works fine now! – Stanislav Popovych Jul 08 '17 at 21:38
  • @StanislavPopovych great! you should answer your own question =) – Rodrigo E. Principe Apr 26 '18 at 16:04

1 Answers1

8

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)
David Boho
  • 2,646
  • 20
  • 17