Stopping a loop with user input. in curses

Chatralias chatralias at aol.com
Sun Jul 20 17:09:41 CEST 2003


Hi Alex, 

The only curses that I know are the ones that I use when I have a problem like
the one your facing here, but I think I can help.
Looks like your not stopping the first while loop when user  hits the 'q' key,
your just doing curses.beep() (I assume this makes a sound?).

Seams to me that you can put all of your active (for want of a better word)
code into one while loop so that it is all stoped when the "q" key it hit.
Or add a call to the first while loop from the second while loop so that it
stops. Because the first while loop is running ever since "theClock()" is
called and it never even see the 'q' get pressed. I mean that the code
execution never gets to the second while loop.

Try this... cus I can't with out curses installed.    

...clip..
#! /usr/bin/python

# Import curses module

import curses, time

def main():    
    finished = 0       # which is like saying "not finished" -see while loop 
    stdscr = curses.initscr()

    # Define global colour scheme
    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)

    # Get the screen size
    max_y, max_x = stdscr.getmaxyx()

    # Calculate the clock position relative to the screen size
    clock_x = max_x - 28 

    # Draw the clock
    clockWindow = curses.newwin(3, 26, 1, clock_x)
    clockWindow.bkgd(' ', curses.color_pair(1))
    clockWindow.box()
    clockWindow.refresh()

    
    while not finished:           # so long as finished is 0 this will loop
        # If 'q' is pressed, exit
        c = stdscr.getch()
        if c == ord('q'):
            curses.beep()
            finished = 1
            break

        t = time.asctime()
        clockWindow.addstr(1, 1, t)
        clockWindow.refresh()
        time.sleep(1)

if __name__ == '__main__':
    curses.wrapper(main)
....end clip...

As you can see I've made a lot of changes.
Let me see if I can explain.
First I put every thing into one function main. 
This assumes that you are not using the "theClock()" function somewhere else,
so if you are then don't do this. 
But, the point is, that if you look at the first variable I defined in the
"main()" function - "finished = 0" - then look at the while loop,- "while not
finished:"- when the user types 'q', the finished variable is set set to 1 and
every thing stops. 

Hope it works because I don't have a way to test it. 

Ray
Rastm2 at aol.com




More information about the Python-list mailing list