Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Successive ipywidgets buttons

I'm trying to make a successive process of buttons clicks using ipywidgets buttons.

Click on button 1 is supposed to clear button 1 and display button 2 etc...

It looks like the introduction of the wait variable make my purge function unreachable, and I don't understand why.

from ipywidgets import Button
from IPython.display import display, clear_output

def purge(sender):
    print('purge')
    clear_output()
    wait=False

for i in range(5):
    print(f'Button number :{i}')
    btn = widgets.Button(description=f'Done', disabled=False,
                        button_style='success', icon='check')
    btn.on_click(purge)
    display(btn)
    wait=True
    while wait:
        pass
like image 706
Xavier M. Avatar asked Mar 22 '26 10:03

Xavier M.


1 Answers

Your while wait: pass loop is an extremely tight loop that will likely spin a CPU core at 100%. This will bog down not just your program but perhaps even your entire computer.

I think what you want to do is to display the next button not in the for loop, but in the on_click callback.

from ipywidgets import Button
from IPython.display import display, clear_output

def purge(i):
    print(f'Button number :{i}')
    clear_output()
    btn = widgets.Button(description=f'Done', disabled=False,
                        button_style='success', icon='check')
    btn.on_click(purge, i + 1)
    display(btn)

purge(1)

Then you can put an if i == 5 in your function to do something else when they reach the last button.

like image 99
Ronald Avatar answered Mar 23 '26 23:03

Ronald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!