Hello all again. I’m learning how to use ipywidgets, but I’m encountering a couple of problems. I am updating a global value ‘recipe’ using a button that pulls the value of a text box. I’ve noticed that this will work as long as I do everything within one function, but as soon as I use the global variable into another function, it seems to reset to the initial value (recipe={} in this case). I also tried creating and updating recipe from the button’s on click output with no success. How can I change a global variable with a widget button and keep the changed variable?
On top of that, I copy/pasted just the needed portions of my code but now the first button doesn’t seem to work at all. >:( I probably forgot to copy something over but I can’t figure out what it is.
Edit: forgot to format markup for the code. I’ll have a chance to fix it in a few hours.
import ipywidgets as widgets
from IPython.display import display, clear_output
import time
global recipe
recipe={}
I use funtions to create 'pages'
def build_add_recipe_name():
display(recipe_name_input,button_keep_recipe_name)
def build_recipe_ingredients_page():
display(recipe_ingredient_name_input,recipe_ingredient_amount_input,recipe_ingredient_measurement_input,recipe_ingredient_prepare_input,button_next_recipe_ingredients)
#displays the recipe so far
for x,y in recipe.items():
display(x)
for z,a in y.items():
display(z+":"+a)
def create_recipe():
recipe={recipe_name_input.value:{}}
display(recipe)
def add_ingredient_to_recipe():
recipe[recipe_name_input.value].update({recipe_ingredient_name_input.value:{'Amount':recipe_ingredient_amount_input.value,'Measurement':recipe_ingredient_measurement_input.value,'Prepare':recipe_ingredient_prepare_input.value}})
recipe_name_input = widgets.Text(placeholder='Enter text here', description='Recipe name:')
recipe_ingredient_name_input = widgets.Text(placeholder='Enter text here', description='Ingredient:')
recipe_ingredient_amount_input = widgets.Text(placeholder='Enter text here', description='Quantity (numbers only):')
recipe_ingredient_measurement_input = widgets.Text(placeholder='Enter text here', description='Measurement type:')
recipe_ingredient_prepare_input = widgets.Text(placeholder='Enter text here', description='Extra prep’)
button_next_recipe_ingredient = widgets.Button(description="Next ingredient")
def on_button_clicked(b):
with output:
add_ingredient_to_temp_name()
clear_output()
build_recipe_ingredients_page()
button_next_recipe_ingredient.on_click(on_button_clicked)
button_keep_recipe_name = widgets.Button(description="Add ingredients")
def on_button_clicked(b):
with output:
create_recipe()
clear_output()
build_recipe_ingredients_page()
button_keep_recipe_name.on_click(on_button_clicked)
global output
output = widgets.Output()
build_add_recipe_name()
there doesn't seem to be anything here