简体   繁体   中英

Is it possible to get multiple buttons with different outputs using a single function in Python?

I created a button in Python Jupyter Notebook and labelled it as Label1 .

I have a list called a containing numbers from 1 to 5.

I wrote a function on_button_clicked such that on clicking the button, it returns the 5 times the first item in a . So on clicking Label1 button, it returns 5.

My code looks like follows:

from IPython.display import display
from ipywidgets import widgets

button1 = widgets.Button(description = "Label1")

output = widgets.Output()

display(button1, output)

a = [1,2,3,4,5,6]

def on_button_clicked(x):
    with output:
        print (a[0]*5)

button1.on_click(on_button_clicked)

The screenshot is attached to display how the button looks like: 在此处输入图像描述

I want to have four more buttons: Label2 , Label3 , Label4 and Label5 .

When I tried to write a nested function for the button and embedded function,

def get_labels(x):
    a = [1,2,3,4,5]
    button = widgets.Button(description = f"Label{x}")
    output = widgets.Output()
    
    display(button, output)
    
    def on_button_clicked(x):
        with output:
            print (a[x-1]*5)
            
    button.on_click(on_button_clicked)

label2 = get_labels(2)

I got: 在此处输入图像描述

TypeError: unsupported operand type(s) for -: 'Button' and 'int'

It seems that a callback needs to be assigned for each on_click() which is basically a function. My question is: is it possible to write a single function to assign callback for each button or should they be individual for each button? How would the function look like?

You could write something like that:

from IPython.display import display
from ipywidgets import widgets

a = [1,2,3,4,5]
N_buttons=5
buttons=[widgets.Button(description = 'Label'+str(i+1)) for i in range(N_buttons)]
outputs=widgets.HBox([items for items in buttons])
def on_button_clicked(x):
     index_button=int(x.description[-1])
     print('Label'+str(index_button)+' button:'+str(a[index_button-1]*5))

for i in range(N_buttons):
  buttons[i].on_click(on_button_clicked)

display(outputs)

Creating the buttons iteratively and then associating for each button a common on_button_clicked function that use the button's description to index your list a .

The output of this code can be seen below: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM