Search code examples
pythoncursesurwid

Print and update a matrix in-place


I have a matrix represented as a list of lists (but can easily change this representation if it would help). I will be updating this matrix as the program runs. I would like to have the matrix displayed on the screen in some standard way. So something like

enter image description here

I would like this display to update as the program runs.

For example,

def updatematrix():
#Change some entries in the matrix

A = [[3,2,3],[1,2,1],[2,8,6]]
while(True):
    updatematrix()
    display(A) #This would ideally change the display in place.

What is a good way of doing this? (In fact I will be changing entire columns and rows and will eventually want to make the changed row/column be in a different color.)

I am happy to use any free libraries that might be useful.


Solution

  • I'd suggeest using the curses library, which is part of the standard python libraries http://docs.python.org/2/library/curses.html

    I've included a bit of a hacked together example

    import curses
    import time
    
    mywindow = curses.initscr()
    
    matrix = [[3,2,3],[1,2,1],[2,8,6]]
    
    def updateMatrix(m):
        m[1][1] = m[1][1] * 2
        return m
    
    def getMarixString(m):
        x = ''
        for row in m:
            x += ' '.join(str(item) for item in row)
            x += "\n"
        return x
    
    z = 10
    while z > 1:
        matrix = updateMatrix(matrix)
        mywindow.addstr(0,0, getMarixString(matrix))
        mywindow.refresh()
        z -= 1
        time.sleep(3)
    
    curses.endwin()
    quit()