-1

there. Can anyone tell me what I did wrong in the code? Why the timer function doesn't appear in the box?

import curses
from datetime import datetime

stdsrc= curses.initscr()

SPACE_KEY = ord(' ')

box1 = curses.newwin(20, 30, 10, 10)
box1.box()  
def run(win):

    win.timeout(1000) 
    start = datetime.now()
    while True:
        now = datetime.now()
        minutes, seconds = divmod((now - start).total_seconds(), 60)
        win.addstr(0, 0, "%02d:%02d" % (minutes, round(seconds)))

        c = win.getch() # c variable to get user character
        if c == SPACE_KEY: 
            break

box1.refresh()  

curses.wrapper(run)

curses.endwin()
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
user7519
  • 17
  • 2

2 Answers2

0

The first two arguments to addstr are the coordinates to start the text. In you code you are starting the text at the coordinates 0,0, whereas your box starts at coordinates 20,30.

maxymoo
  • 35,286
  • 11
  • 92
  • 119
0

The timer does not appear in the box because of these two reasons:

  • the timer is written to the wrong window, and

  • the window that you are reading (using getch) repaints and overwrites the box.

Here is a revised example which makes the box a subwindow of win, and (by the way) moves the timer away from the box border:

import curses
from datetime import datetime

SPACE_KEY = ord(' ')

def run(win):
    box1 = win.subwin(20, 30, 10, 10)
    box1.box()  

    win.timeout(1000) 
    start = datetime.now()
    while True:
        now = datetime.now()
        minutes, seconds = divmod((now - start).total_seconds(), 60)
        box1.addstr(1, 1, "%02d:%02d" % (minutes, round(seconds)))
        box1.refresh()  

        c = win.getch() # c variable to get user character
        if c == SPACE_KEY: 
            break

stdsrc = curses.initscr()
curses.wrapper(run)

The call to initscr is unnecessary; curses.wrapper does that. If you remove that initscr call, the screen will use white-on-black. But getting the colors right would be another question.

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
  • Hi, thank you so much. It works now just that I need to adjust the coordinate of the box and the timer like @maxymoo had mentioned above. Box1 shouldn't start at the coordinate of 20, 30 since it's outside of the coordinate of the timer (1, 1). So, what I did is make the coordinate of box1 to 0, 0 and timer to 10, 20 (somewhere close to the middle of the box). Can you also recommend some books or any website that allow me to learn this curses because I'm quite new to this? – user7519 Apr 16 '17 at 08:48