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

时间:2015-08-25 12:50:33

标签: ipython ipython-notebook

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

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(HTML("...."))函数之前调用display(widgets(...))函数,我得到以下输出(顺序相反): enter image description here

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

enter image description here

我无法理解。

1 个答案:

答案 0 :(得分:1)

您可以使用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()