将ipywidgets放入HTML放入Jupyter笔记本中 [英] Place ipywidgets into HTML into Jupyter notebook

查看:494
本文介绍了将ipywidgets放入HTML放入Jupyter笔记本中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的最小示例中,我可以创建与Jupyter笔记本和显示在笔记本中的HTML表格交互的按钮.

With the following minimal example, I can create buttons which interact with the Jupyter notebook and an HTML table, which is displayed in the notebook.

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表中.我尝试研究方法Widget._ipython_display_(),但这不允许我使用自己的html表中的按钮.

I now would like to place the buttons in the html table. I tried investigating the method Widget._ipython_display_() but this does not allow me to use the button inside my own html table.

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

(Please see the small table as an example. I want to place the buttons in a large table and use the buttons to delete rows from a database.)

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

In this question, the wanted to know, how to place widgets relative to each other. Here, I want to place the widgets inside other HTML code.

推荐答案

似乎没有简单的方法可以实现此目的.您将必须构建一个自定义的ipywidget来显示表格,或者手动编写具有完全控制权的HTML按钮的代码.

There doesn't seem to be an easy way to achieve this. You will either have to build a custom ipywidget to display a table, or manually write the code for an HTML button of which you'll have full control.

我能找到的最好的方法是一种使用HBox内的VBoxes数组模拟表的方法:

The best I could find was a way to emulate a table using an array of VBoxes inside an HBox:

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)

结果:

这篇关于将ipywidgets放入HTML放入Jupyter笔记本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆