通过以下最小示例,我可以创建与 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>'
))
我现在想将按钮放在 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)
结果:
关于python - 将 ipywidgets 放入 HTML 到 Jupyter notebook 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37528992/