Search code examples
pythondrawcurses

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?


Solution

  • 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()