Search code examples
pythoncurses

Why can't I addstr() to last row/col in python curses window?


Using Python, I'm trying to write the cursor location to the lower right corner of my curses window using addstr() but I get an error. ScreenH-2 works fine but is printed on the 2nd line up from the bottom of the winddow. ScreenH-1 does not work at all. What am I doing wrong?

import curses

ScreenH = 0
ScreenW = 0
CursorX = 1
CursorY = 1

def repaint(screen):   
   global ScreenH
   global ScreenW
   global CursorX
   global CursorY

   ScreenH, ScreenW = screen.getmaxyx()
   cloc = '   ' + str(CursorX) + ':' + str(CursorY) + ' '
   cloclen =  len (cloc)
   screen.addstr (ScreenH - 1, ScreenW - cloclen, cloc,  curses.color_pair(1));


def Main(screen):
   curses.init_pair (1, curses.COLOR_WHITE, curses.COLOR_BLUE)
   repaint (screen)   

   while True:
      ch = screen.getch()
      if ch == ord('q'):
         break

      repaint (screen)     


curses.wrapper(Main)

  File "test.py", line 17, in repaint
    screen.addstr (ScreenH - 1, ScreenW - cloclen, cloc,  curses.color_pair(1));
_curses.error: addstr() returned ERR

Solution

  • You need to substract 1 from the width as you did for the height. Otherwise the string will exceed the width of the screen.

    screen.addstr(ScreenH - 1, ScreenW - 1 - cloclen, cloc,  curses.color_pair(1))
                                       ^^^