Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't my curses box draw?

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?

like image 366
Kyle Sponable Avatar asked Nov 29 '22 12:11

Kyle Sponable


2 Answers

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()
like image 177
Thomas Dickey Avatar answered Dec 06 '22 20:12

Thomas Dickey


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()
like image 40
furas Avatar answered Dec 06 '22 21:12

furas