0

I am planning to return the value of gameMode because I would like to use the output of gameMode being easy medium or hard for a game I am doing but there is always a name error. Is there any way to solve this? picture of the error: enter image description here

from ipywidgets import Button, HBox

Modes = ['Easy', 'Medium','Hard']

switch = [Button(description=name) for name in Modes]

combined = HBox([items for items in switch])

def upon_clicked(btn):
    gameMode=btn.description.lower()
    for n in range(len(Modes)):
        switch[n].style.button_color = 'gray'
    btn.style.button_color = 'pink'

for n in range(len(Modes)):
    switch[n].on_click(upon_clicked)

display(combined)
gameMode

1 Answers1

0

You need to return a value from the on_click handler or be able to set an attribute. Using Return output of the function executed 'on_click' as a base example, you could do something like this:

from ipywidgets import widgets, HBox
from IPython.display import display
from traitlets import traitlets

output = widgets.Output()

class LoadedButton(widgets.Button):
    """A button that can holds a value as a attribute."""

    def __init__(self, value=None, *args, **kwargs):
        super(LoadedButton, self).__init__(*args, **kwargs)
        # Create the value attribute.
        self.add_traits(value=traitlets.Any(value))
        self.style.button_color="gray"

buttons = [
    LoadedButton(description="Easy", value="easy"),
    LoadedButton(description="Medium", value="medium"),
    LoadedButton(description="Hard", value="hard")
]
        
def change_btn_color(btn):
    output.clear_output()
    for button in buttons:
        button.style.button_color="gray"
    btn.style.button_color = 'pink'
    with output:
        print(btn.value)

for button in buttons:
    button.on_click(change_btn_color)
    
combined = HBox(buttons)
display(combined, output)

after you click on a button, in the next cell, you can extract the output of a button with:

print(output.outputs[0]["text"])

I've never used ipywidgets before so hopefully someone else can come along with a better solution, but this does work

Hussain Hassam
  • 319
  • 1
  • 5