Search code examples
pythondatabricksazure-databricks

Databricks notebook ipywidgets not working as expected


I am working on Azure databricks(IDE). I wanted to create a button which takes a text value as input and on the click of a button a function needed to be run which prints the value entered. For that I created this code:

import ipywidgets as widgets

def my_function(param):
    print(f"The parameter is: {param}")

text_input = widgets.Text(description="Enter text:")
button = widgets.Button(description="Click Me!")

display(text_input)
display(button)

def on_button_click(b):
    my_function(text_input.value)

button.on_click(on_button_click)

But when I click the button, nothing happens. It should run the my_function and print the input text.

Strangely this exact code works fine when I run it in jupyter notebook.

I am not able to make it work in Azure Databricks.

Any insights would be helpful


Solution

  • Using the same code as you, I was unable to generate the function call on button click. However, making the following changes worked.

    import ipywidgets as widgets
    
    def my_function(param):
        print(f"The parameter is: {param}")
    
    text_input = widgets.Text(description="Enter text:")
    button = widgets.Button(description="Click Me!")
    output = widgets.Output()
    
    display(text_input)
    display(button, output)
    
    def on_button_click(b):
        with output:
            print("button is clicked")
            my_function(text_input.value)
    
    button.on_click(on_button_click)
    

    enter image description here