[Tutor] curses.textpad.Textbox.gather()

Alex Kleider alexkleider at gmail.com
Sun Nov 21 22:40:57 EST 2021


"""
I expect this will be of interest only to those using the curses
module.

I found that the Textbox.gather method seems incapable of returning
a string without a trailing space. The problem is easily solved by
using str.strip() as in the last line of my function (provided below)
but I'm wondering if there's a better way. Specifically to provide the
user with the option of having or not having a trailing space.
"""

import sys
import curses as cur
from curses.textpad import Textbox

def edited_text(scr, text, y,x):
    """
    Provides the editing capability:
    Returns the edited (or not) version of text.
    Editing window begins at (y,x) of the <scr>een.
    """
    scr.addstr(y,0, "Edit the text then Ctrl-G to exit",
               cur.A_BOLD)
    scr.refresh()
    # create the text box with border around the outside
    tb_border = cur.newwin(3,52,y+1,x)
    tb_border.box()
    tb_border.refresh()
    tb_body = cur.newwin(1,50,y+2,x+1)
    tb = Textbox(tb_body)
    for ch in text:  # insert starting text
        tb.do_command(ch)
    tb.edit()  # start the editor running, Ctrl-G ends
    s2 = tb.gather()  # fetch the contents
    scr.clear()  # clear the screen
#   return s2
    return s2.strip()

def main(scr):
    text = "Some text to be or not to be edited."
    new_text = edited_text(scr, text, 5,4)
    scr.clear()
    scr.addstr(8,0, 'Your modified text: "{}"'.format(new_text))
    scr.getch()  # does a refresh

cur.wrapper(main)

close = """
TIA

Cheers,
Alex Kleider
"""


More information about the Tutor mailing list