将ipywidgets放入HTML到Jupyter笔记本

时间:2016-05-30 15:14:53

标签: python html jupyter-notebook ipywidgets

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

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>'
    ))

产生的结果是: screenshot of table and buttons

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

(请参阅小表作为示例。我想将按钮放在一个大表中,然后使用按钮从数据库中删除行。)

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

1 个答案:

答案 0 :(得分:5)

似乎没有一种简单的方法可以实现这一目标。您将需要构建自定义ipywidget以显示表,或者手动编写您可以完全控制的HTML按钮的代码。

我能找到的最好的方法是使用HBox内部的VBox数组来模拟表格:

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)

结果:

enter image description here