ipywidgets button onclick event is not raising the onclick method

Viewed 1421
import ipywidgets as widgets

button = widgets.Button(description="Click Me!")
output = widgets.Output()

display(button, output)

def on_button_clicked():
    print("button clicked")

button.on_click(on_button_clicked)

The button shows up.. but when I click on the button, I expect to see the message "button clicked" to show up. But that's not happening.

Is there something I'm missing here?
I am using vscode to run my jupyter notebook.

1 Answers

You need to pass the button b in the definition of your on_button_clicked function. See examples in the doc here and code below:

import ipywidgets as widgets

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)

And the output gives:

enter image description here

Related