将 ipywidgets 放入 HTML 放入 Jupyter notebook

Place ipywidgets into HTML into Jupyter notebook

通过以下最小示例,我可以创建与 Jupyter 笔记本交互的按钮和显示在笔记本中的 HTML table。

import ipywidgets
from IPython.display import display

from IPython.core.display import HTML

def func(btn):
    print('Hi!')

btn1 = ipywidgets.Button(description="Click me!")
btn1.on_click(func)
btn2 = ipywidgets.Button(description="Click me!")
btn2.on_click(func)
display(btn1)
display(btn2)

display(HTML(
        '<table>' +
        '<tr><td>Something here</td><td>Button 1 here</td></tr>' +
        '<tr><td>Something here</td><td>Button 2 here</td></tr>' +
        '</table>'
    ))

产生的结果是:

我现在想将按钮放在 html table 中。我尝试研究 Widget._ipython_display_() 方法,但这不允许我使用我自己的 html table.

中的按钮

(请以小 table 为例。我想将按钮放在大 table 中,并使用按钮从数据库中删除行。)

中,想知道如何相对于彼此放置小部件。在这里,我想将小部件放在其他 HTML 代码中。

似乎没有一种简单的方法可以实现这一点。您将必须构建一个自定义的 ipywidget 来显示 table,或者手动编写您可以完全控制的 HTML 按钮的代码。

我能找到的最好的方法是在 HBox 中使用 VBox 数组来模拟 table:

import ipywidgets as widgets
from IPython.display import display

def func(btn):
    print('Hi!')

btn1 = widgets.Button(description="Click me!")
btn1.on_click(func)
btn2 = widgets.Button(description="Click me!")
btn2.on_click(func)

# This is where you fill your table
cols = [
    # Each tuple contains a column header and a list of items/widgets
    ('Col1', ['hello', 'goodbye']),
    ('Col2', ['world', 'universe']),
    ('Buttons', [btn1, btn2]),
]

vboxes = []
for header, data in cols:
    vboxes.append(widgets.VBox([widgets.HTML('<b>%s</b>' % header)] + [
        d if isinstance(d, widgets.Widget) else widgets.HTML(str(d)) for d in data],
    layout=widgets.Layout(border='1px solid')))

hbox = widgets.HBox(vboxes)

display(hbox)

结果: