python-3.xcommand-line-interfacepython-curses

Python curses border doesn't redraw; window resizing ruins border


I have a very simple curses project (I started learning this library for a CLI-themed text game) and want to have a border around my window. However, running screen.border() does NOT redraw my screen's border, which makes resizing the window completely ruin the border.

Before resize: Before window resize After resize: After window resize Current code:

if __name__ == "__main__":

    import curses

    screen = curses.initscr()
    curses.cbreak()
    curses.curs_set(0)
    curses.noecho()
    curses.start_color()
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    running = True
    key = None

    while running:
        max_y, max_x = screen.getmaxyx()
        screen.border()
        screen.addstr(1, 1, "Key Code:", curses.color_pair(1))
        screen.addstr(2, 1, str(key))
        screen.refresh()
        screen.timeout(20)
        old_key = key
        key = screen.getch()

        if key >= 0:

            match key:

                case 27:
                    running = False

                case curses.KEY_RESIZE:
                    pass

                case _:
                    pass

        else:
            key = old_key

        screen.erase()

    curses.endwin()

Solution

  • Necro response, I know. You probably figured this out by now but since I am currently working on curses i thought I'd answer this: It doesn't work because you declare

    screen = curses.initscr()
    

    outside of the loop. That basically takes the console once when you run the application and initializes the screen as a window, basically setting that windows properties. Later you call upon that window with

    screen.border()
    

    which is why the proportions don't work. It takes the dimensions of the originally initialized window so it keeps redrawing the borders when you resize the window but it doesn't actually change the window size.