How to align widget buttons in IPython notebook

2019-05-01 12:51发布

问题:

I have the following peace of code

from ipywidgets import widgets
from IPython.display import display
import numpy as np

class Test(object):
    def __init__(self, arraylen):
        self.a = np.random.randn(arraylen)
        self.button = widgets.Button(description = 'Show')
        self.button.on_click(self.show)
        display(self.button)

        self.button1 = widgets.Button(description = 'Show1')
        self.button1.on_click(self.show)
        display(self.button1)

    def show(self, ev = None):
        np.savetxt('test',self.a)
        self.button.disabled = True


test = Test(10)

The output is two buttons in a column as shown here:

Would it also be possible, to embed the buttons in a HTML table (where I could choose them to be in a row), or any other organization scheme? Maybe it could look like this:

回答1:

You could use (a very basic example):

from IPython.display import display
from ipywidgets import widgets
button1 = widgets.Button(description = 'Button1')
button2 = widgets.Button(description = 'Button2')
display(widgets.HBox((button1, button2)))

Here you can find basic and more complete examples about the use of the widgets. If you are using Jupyter you should adapt some info (from ipywidgets import widgets instead from IPython.html import widgets,...).