Animation with ipythonblocks

For more on ipythonblocks see the home page at https://github.com/jiffyclub/ipythonblocks.

In [1]:
from ipythonblocks import BlockGrid
In [2]:
import time
from IPython.display import clear_output

It's possible to do animation of sorts using IPython's clear_output function.

In [3]:
grid = BlockGrid(3, 3)

previous_block = None

for block in grid:
    clear_output()
    block.green = 255
    
    if previous_block:
        previous_block.green = 0
    
    grid.show()
    
    previous_block = block
    
    time.sleep(0.2)

And this is so much fun that it's been added to ipythonblocks: one way is to use the BlockGrid.animate() method. The .animate() method takes an optional stop_time keyword to control the amount of time between loop steps.

In [4]:
grid = BlockGrid(3, 3)

previous_block = None

for block in grid.animate():
    block.green = 255
    
    if previous_block:
        previous_block.green = 0
    
    previous_block = block

And another way, if not iterating over the grid, is to use the BlockGrid.flash() method. .flash() takes an optional display_time keyword that controls for how long each frame is displayed. The default is 0.2 seconds.

In [5]:
grid = BlockGrid(3, 3)

previous_block = None

indices = [[(0, 0), (0, 2), (2, 0), (2, 2)], [(0, 1), (1, 0), (1, 2), (2, 1)]] * 10

for ind in indices:
    for i in ind:
        grid[i[0], i[1]].green = 255
    
    grid.flash(display_time=0.1)
    
    for i in ind:
        grid[i[0], i[1]].green = 0

grid.show()
In []:
 
Back to top