How to get basic ipywidgets text box working properly in JupyterLab 3.2.9?

Viewed 504

I'm playing with the Reddit API and I'd like to have a basic text box for the user to input a subreddit to search. I want this interactivity so that I can (hopefully) post my notebook on github or nbviewer and have someone else try it. When I try to run my code, several things happen:

  1. The notebook continues to execute code cells instead of waiting for user to input a subreddit
  2. If I execute the cells manually, I can get the text box to appear, but then nothing happens when I hit 'Enter'.

Below is my code:

def onchange(change):
    with caption:
        print(change.value)
        
sub = widgets.Text(placeholder='Enter subreddit', description='r/')
caption = widgets.Output()

display(sub)
sub.on_submit(onchange)

And here is what it looks like when I execute the cell manually:

My cell output

1 Answers

You need to display(output) after your display(sub) initially, and go from there.

The output widget is capturing the output of the Text widget, so you need to display that output widget too.

You might be able to make a simpler implementation using the interactive options with ipywidgets, but I prefer the more explicit version using observe and on_click etc.

Related