6

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.

1 Answer 1

8

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

5 Comments

I copied your exact example, but it does not seem to work. I do not se any output.
I just tested it on Jupyterlab 1.1.4. and it also outputs nothing. It works however on Jupyter notebook.
Yes might be, but I need it to work on jupyterlab. Sorry I did not post that info earlier...
I think you have to create the output widget then.
If this happens to be helpful, I restarted jupyter-lab from the terminal after installing ipywidgets and the button displayed, and the button displays; it works when there is no code currently running, and does not work when, say, there is a loop running. I am looking for a graceful way to exit a loop by clicking a button, would be great for ML experiments.

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.