psj01
psj01

Reputation: 3245

ipywidgets button onclick event is not raising the onclick method

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.

Upvotes: 6

Views: 8233

Answers (1)

jylls
jylls

Reputation: 4705

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

Upvotes: 8

Related Questions