有没有办法在同一输出单元格中的小部件之前在 IPython 笔记本中显示 HTML 代码?

Is there a way to display HTML code in an IPython notebook before widgets in the same output cell?

我正在尝试使用小部件编写 IPython 笔记本。为此,我想要一些 HTML headers,然后是输入小部件。我是这样实现的:

from ipywidgets import widgets
from IPython.display import display
from IPython.core.display import HTML

class buttons(object):
    def __init__(self):

        self.buttons = []
        for i in xrange(6):

            self.buttons.append( widgets.Button(description = str(i)))
            self.buttons[-1].on_click(self.handle_submit)
            self.buttons[-1].margin=20

        display(HTML("<h1> Heading </h1>"))

        display( widgets.HBox((self.buttons)) )

        self.text = widgets.Text(value="21")
        display(self.text)

    def handle_submit(self, sender):
        self.show(int(self.text.value))

    def show(self, x=None):
        print(1+1)

b = buttons()

然而,即使我在 display(widgets(...)) 函数之前调用 display(HTML("....")) 函数,我也会得到以下输出(顺序相反):

有没有办法让它看起来像这样:

我想不通。

您可以使用 VBox 一起构建所有内容:

from IPython.display import display
from IPython.core.display import HTML

class buttons(object):
    def __init__(self):

        self.buttons = []
        for i in xrange(6):

            self.buttons.append( widgets.Button(description = str(i)))
            self.buttons[-1].on_click(self.handle_submit)
            self.buttons[-1].margin=20

        self.text = widgets.Text(value="21")

        self.header = widgets.HTML(description='',value='<h1> Heading </h1>')
        self.everything = widgets.VBox([self.header,widgets.HBox((self.buttons)),self.text])
        display(self.everything)

        #display(HTML("<h1> Heading </h1>"))

        #display( widgets.HBox((self.buttons)) )


        #display(self.text)

    def handle_submit(self, sender):
        self.show(int(self.text.value))

    def show(self, x=None):
        print(1+1)

b = buttons()