python - 将 ipywidgets 放入 HTML 到 Jupyter notebook 中

标签 python html jupyter-notebook ipywidgets

通过以下最小示例,我可以创建与 Jupyter notebook 交互的按钮和显示在 notebook 中的 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 代码中。

最佳答案

似乎没有一种简单的方法可以实现这一目标。您将必须构建一个自定义的 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

关于python - 将 ipywidgets 放入 HTML 到 Jupyter notebook 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37528992/

相关文章:

python - h5py.File(path) 无法识别文件夹路径

python - 使用 jupyter 笔记本在一个图上绘制来自 3 个数据集的 3 个图表

python - 我的 Python 3 文件代码没有附加或读取文件的权利

python - 如何在 Windows 10 上使用 Cx_Freeze 制作 exe,包括 PyQt5 和 OpenCV

javascript - 只需要获取 ID 的一部分(最后一个下划线之后的所有内容)

python - 使用 matplotlib 时,带有 Anaconda 5.1.0 或更高版本的 Jupyter-Notebook 中的内存泄漏

python - 如何设置字体大小或标签大小以适合所有设备

python - 如何在Python中将固定长度文件转换为csv文件?

javascript - 获取所有表单数组到JS数组

javascript - 单击时更改图像的 z-index