0

I was wondering if I can make an output interactively run a piece of code. So if for example I had a class (parts in pseudo-code):

import numpy as np

class test(object):
    def __init__():
        self.a = np.random.randn(10)
        print ## Interactive Output: Click me to view data array##

    def show():
        print a

So when I create a class instance it should output some interactive link (maybe in html) or something like that and when I click it, the show() method should be called. However, I have no idea how to achieve that.

1 Answers1

0

You could use the widgets shipped with the notebook (for jupyter they are an independent package).

Something like this could do what you want (Python 3):

from IPython.html 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)

    def show(self, ev = None):
        display(self.a)
        self.button.disabled = True


test = Test(10)
  • You create a button widget when you initialise the class widgets.Button(description = 'Show')
  • Attach an event to it button.on_click(self.show)
  • And display the button display(self.button)
  • In the show method I included a way to disable the button functionality once the array is showed self.button.disabled = True. You can comment this line if you want to show more times the array.
kikocorreoso
  • 3,999
  • 1
  • 17
  • 26
  • Do you also know if I can arrange the buttons in a html table as well as the output? –  Aug 24 '15 at 09:50
  • You could use a combination of `widgets`, `display` and `HTML`. You should open a new question with what you need as ouput in order to others or I can provide a more accurate answer to this new requirement. – kikocorreoso Aug 24 '15 at 13:00
  • Please find the other question [here](http://stackoverflow.com/questions/32181126/how-to-align-widget-buttons-in-ipython-notebook) –  Aug 24 '15 at 15:13