[Tutor] Simple curses application

Alan Gauld alan.gauld at yahoo.co.uk
Mon Oct 25 13:37:19 EDT 2021


On 25/10/2021 12:40, Julius Hamilton wrote:

> else:
> 
>   # show a menu of imported texts with curses. The user can navigate up and
> down with Vim keys: j and k, and choose one with “enter”. What’s a good way
> to do that with curses? Or a different library?
> 
> scr = curses.initscr()

You should use the curses.wrapper() function for most curses programs,
it catches a lot of common problems and will save your sanity. You only
need to call initscr() if you are doing saome unusual initialisation or
low level control stuff.

The format is:

def main(screen):
   # all your curses code here

curses.wrapper(main)


The wrapper then calls your main function passing it a reference to
the main screen window. It will catch any exit conditions and tidy
up the terminal for you.

> Assuming they select one:
> 
> text = data[selection[text]]
> index = data[selection[index]]
> comments = data[selection[comments]]
> 
> lines = text.splitlines()
> 
> 
> scr.addstr(line[index])
> curses.refresh()
> 
> # How do I listen for user key presses

Use the getch() function.
Note that it returns an int so you need to compare the
value to ord('h') etc.

But note that curses does not provide any kind of mainloop capability
you need to write tat yourself. Something like:

while True:
    key = curses.getch()
    if key in [ ord('q'), ord('Q')]:   # q/Q to exit
       break
    elif key == ord('h'):  # do the h thing
    elif key == ord('j'):  # do the j thing
    etc...

<PLUG class="blatant">
You may find my book on curses useful, it's an Amazon Kindle
ebook and I priced it as low as I could while avoiding having
to pay Amazon for copies sold!

Programming curses in Python

You can also get it in paperback if you prefer.
</PLUG>

Finally, here is the minimal wrapper example from the book:

import curses as cur

def main(win):
    win.addstr(4,4,"Hello world")
    win.refresh()
    win.getch()

cur.wrapper(main)

That just displays the message and waits for the user
to hit any key to exit.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list