Write me a python script inside a jupyter notebook that allows a user to continually add text from a free text input into a list and then displays the resulting list below the input fields
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a Python script inside a Jupyter Notebook that allows a user to continually add text from a free text input into a list and displays the resulting list below the input fields:
python
from IPython.display import display
import ipywidgets as widgets
# Create an empty list to store the user's input
user_input_list = []
# Create a text input widget
text_input = widgets.Text(
value='',
placeholder='Enter text',
description='Text:',
disabled=False
)
# Create a button widget
add_button = widgets.Button(
description='Add',
disabled=False,
button_style='success',
tooltip='Add text to the list'
)
# Create an output widget to display the list
output = widgets.Output()
# Function to handle button click event
def on_button_clicked(b):
user_input = text_input.value
if user_input:
user_input_list.append(user_input)
text_input.value = '' # Clear the input field
with output:
output.clear_output()
print("User Input List:")
for item in user_input_list:
print("- " + item)
# Attach the button click event handler
add_button.on_click(on_button_clicked)
# Display the widgets
display(text_input, add_button, output)
Explanation:
We import the necessary modules: display from IPython.display and ipywidgets for creating interactive widgets.
We create an empty list called user_input_list to store the user's input.
We create a text input widget using widgets.Text(). This widget allows the user to enter text.
We create a button widget using widgets.Button(). This button will be used to add the user's input to the list.
We create an output widget using widgets.Output(). This widget will be used to display the resulting list.
We define a function called on_button_clicked() that will be called when the button is clicked. This function retrieves the user's input from the text input widget, appends it to the user_input_list, clears the input field, and updates the output widget to display the updated list.
We attach the on_button_clicked() function to the button's click event using add_button.on_click().
Finally, we use display() to display the text input widget, the button widget, and the output widget.
When you run this script in a Jupyter Notebook, you will see a text input field and an "Add" button. You can enter text into the input field and click the "Add" button to add the text to the list. The resulting list will be displayed below the input fields, with each item preceded by a hyphen ("-"). You can continue adding text to the list as needed.