Question

I have an object (derived from ElementTree) that holds an SVG image. The object has a method _repr_svg_ so that it can be rendered as an SVG image in an iPython notebook. Suppose now that in a cell I run

In [n]: object
Out[n]: # drawing appears here

and then I modify the object. Is it possible to have iPython automatically re-evaluate the cell so that the drawing will be updated?

Is it possible, for example, that a specific cell is re-evaluated after every successful evaluation of any other cell in the notebook?

Was it helpful?

Solution

I'm not sure regarding using _repr_svg_, but you can create rich content with IPython 2.0 (current development version, available from Master branch at github) that updates according to various events.

You can see an example here: http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/widgets/Variable%20Inspector.ipynb

The magic is done in the line self._ipython.register_post_execute(self._fill)

which calls "fill" function whenever new cell is executed. In your case, "_fill" function should draw an SVG instead of updating an HTML table.

Simple example (works only on IPython 2.0). This draws an sVG circle according to the value of the variable r

ipython = get_ipython()
from IPython.html import widgets

###del ipython._post_execute[make_svg]  ##add it if you rerun the cell. 
r = 50
def make_svg():
    svg_code = """<svg width="300" height="200">
    <circle cx="50" cy="50" r="%d" stroke="black" stroke-width="3" fill="red" />
</svg>
""" % r
    _modal_body_label.value = "<br>%s<br>" % svg_code 
ipython.register_post_execute(make_svg)


_modal_body_label = widgets.HTMLWidget(value = 'Not hooked')


_modal_body_label
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top