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?

4
  • What do you mean by "does not work"? Commented Jul 8, 2017 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. Commented Jul 8, 2017 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! Commented Jul 8, 2017 at 21:38
  • @StanislavPopovych great! you should answer your own question =) Commented Apr 26, 2018 at 16:04

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.