2016-05-30 172 views
9

通過以下最簡單的示例,我可以創建與Jupyter筆記本交互的按鈕和顯示在筆記本中的HTML表格。將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代碼中。

回答

3

似乎沒有一種簡單的方法來實現這一點。您將不得不構建一個自定義ipywidget來顯示一個表,或者手動編寫一個HTML按鈕的代碼,您將完全控制它。

我能找到一個方法,模擬表,可以使用縱向方框的數組與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) 

結果:

enter image description here