0

I create many buttons in my script. I need to call a function by these buttons. But the function is working only in the very last button. What is wrong?

import ipywidgets as widgets
from IPython.core.display import display, HTML

def fn(b):
    print(b.description+" clicked.")

for i in range(10):
    btn= widgets.Button(
    description='Button '+str(i),
    disabled=False,
    button_style='info', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Delete')
    display(btn)

btn.on_click(fn)

1 Answers1

0

btn.on_click(fn) is outside your loop so btn referes to the last button instance in your loop

Coding this way will fix the problem

for i in range(10):
  #loop previous body
  btn.on_click(fn)
IQbrod
  • 2,060
  • 1
  • 6
  • 28