Question

I am toying with curses and I can't get a box to draw on the screen. I created a border which works but I want to draw a box in the border

here is my code

import curses 

screen = curses.initscr()

try:
    screen.border(0)
    box1 = curses.newwin(20, 20, 5, 5)
    box1.box()
    screen.getch()

finally:
    curses.endwin()

any advice?

Was it helpful?

Solution 2

From curses docs:

When you call a method to display or erase text, the effect doesn’t immediately show up on the display. ...

Accordingly, curses requires that you explicitly tell it to redraw windows, using the refresh() method of window objects. ...

You need screen.refresh() and box1.refresh() in correct order.

Working example

#!/usr/bin/env python

import curses 

screen = curses.initscr()

try:
    screen.border(0)

    box1 = curses.newwin(20, 20, 5, 5)
    box1.box()    

    screen.refresh()
    box1.refresh()

    screen.getch()

finally:
    curses.endwin()

or

#!/usr/bin/env python

import curses 

screen = curses.initscr()

try:
    screen.border(0)
    screen.refresh()

    box1 = curses.newwin(20, 20, 5, 5)
    box1.box()    
    box1.refresh()

    screen.getch()

finally:
    curses.endwin()

You can use immedok(True) to automatically refresh window

#!/usr/bin/env python

import curses 

screen = curses.initscr()
screen.immedok(True)

try:
    screen.border(0)

    box1 = curses.newwin(20, 20, 5, 5)
    box1.immedok(True)

    box1.box()    
    box1.addstr("Hello World of Curses!")

    screen.getch()

finally:
    curses.endwin()

OTHER TIPS

The suggested answer is more complicated than necessary. Rather than use newwin, if you use subwin, it shares memory with the original window, and will be repainted without additional work.

Here is the original program modified to do that (a one-line change):

import curses

screen = curses.initscr()

try:
    screen.border(0)
    box1 = screen.subwin(20, 20, 5, 5)
    box1.box()
    screen.getch()

finally:
    curses.endwin()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top