如何在 ipywidgets 上制作一个自我感知按钮

How to make a self aware button on ipywidgets

我需要编写一个函数来知道单击了哪个按钮来调用它。我正在使用 ipywidgets 和 jupyter notebook。

下面是一些示例代码:

import ipywidgets as widgets

button1 = widgets.Button(description = 'I am button 1')
button2 = widgets.Button(description = 'I am button 2')

def self_aware(caller):
    # Some code I don't know
    pass
    
    
button1.on_click(self_aware)
button2.on_click(self_aware)

widgets.VBox([button1, button2])

单击按钮 1 时,应将其作为参数传递给 self_aware 函数。 例如 print('I am button 1') 或 2 就足够了

您可以访问按钮说明:

def self_aware(caller):
    print(caller.description)