Alex
Alex

Reputation: 44265

How to create a simple Button with output in a python jupyter notebook?

Trying to create a simple button with some output I tried the following code

from IPython.display import display
def clicked():
    print("button has been clicked!")

button_download = widgets.Button(description = 'Test Button')   
button_download.on_click(clicked)
display(button_download)

but when I click on the button I cannot see any output.

I found another example that works, but this is way too complicated:

from IPython.display import display
button = widgets.Button(description="Click Me!")
output = widgets.Output()

display(button, output)

def on_button_clicked(b):
    with output:
        print("Button clicked.")

button.on_click(on_button_clicked)

Do I really need to output thing so I can see the output of a print statement when I click the button?

The system is Jupyterlab 1.1.4.

Upvotes: 6

Views: 15580

Answers (1)

Stanislas Morbieu
Stanislas Morbieu

Reputation: 1827

You only need to add an argument to the clicked function to make it work:

from IPython.display import display
import ipywidgets as widgets


def clicked(arg):
    print("button has been clicked!")

button_download = widgets.Button(description = 'Test Button')   
button_download.on_click(clicked)
display(button_download)

Upvotes: 8

Related Questions