0

I have the piece of code below which wouldn't work unless n_rows > 3 or n_cols > 3. Otherwise I get this error:

    Traceback (most recent call last):
      File "script.py", line 16, in <module>
        curses.wrapper(main)
      File "/usr/lib/python3.8/curses/__init__.py", line 105, in wrapper
        return func(stdscr, *args, **kwds)
      File "script.py", line 10, in main
        window.addstr(2, 2, '2')
    _curses.error: addwstr() returned ERR

This type of error normally happens when printing outside window (which isn't the case here).

    def main(stdscr):
        n_rows = 3
        n_cols = 3
        window = stdscr.subwin(n_rows, n_cols, 0, 0)
        window.addstr(0, 0, '0')
        window.addstr(1, 1, '1')
        window.addstr(2, 2, '2')
    
        stdscr.getch()
    
    
    if __name__ == '__main__':
        curses.wrapper(main)

My question is what explains the necessity for window to be one size larger for it to work?

Hakim
  • 3,225
  • 5
  • 37
  • 75

1 Answers1

1

The program is printing at the lower-right corner of a window and returns an error because it cannot wrap (or scroll up).

The addch manpage says

  • If scrollok is not enabled, writing a character at the lower right margin succeeds. However, an error is returned because it is not possible to wrap to a new line

and scrollok (which is false unless explicitly set):

The scrollok option controls what happens when the cursor of a window is moved off the edge of the window or scrolling region, either as a result of a newline action on the bottom line, or typing the last character of the last line. If disabled, (bf is FALSE), the cursor is left on the bottom line. If enabled, (bf is TRUE), the window is scrolled up one line (Note that to get the physical scrolling effect on the terminal, it is also necessary to call idlok).

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
  • I ended up using `insstr()` instead of `addstr()` as it's doesn't move the cursor after writing to the screen (See [this answer](https://stackoverflow.com/a/28156192/2228912)) – Hakim Jun 10 '21 at 18:22