简体   繁体   English

使用 Python 和 Curses 文本框小部件编辑文本?

[英]Edit text using Python and curses Textbox widget?

Has anybody got a working example of using the curses.textpad.Textbox widget to edit existing text?有没有人有使用 curses.textpad.Textbox 小部件编辑现有文本的工作示例? This is, of course, in a Linux terminal (eg xterm).当然,这是在 Linux 终端(例如 xterm)中。

Found this there is several minutes发现这个有几分钟

import curses
import curses.textpad

stdscr = curses.initscr()
# don't echo key strokes on the screen
curses.noecho()
# read keystrokes instantly, without waiting for enter to ne pressed
curses.cbreak()
# enable keypad mode
stdscr.keypad(1)
stdscr.clear()
stdscr.refresh()
win = curses.newwin(5, 60, 5, 10)
tb = curses.textpad.Textbox(win)
text = tb.edit()
curses.beep()
win.addstr(4,1,text.encode('utf_8'))

I also made a function to make a textbox:我还做了一个函数来制作一个文本框:

def maketextbox(h,w,y,x,value="",deco=None,underlineChr=curses.ACS_HLINE,textColorpair=0,decoColorpair=0):
    nw = curses.newwin(h,w,y,x)
    txtbox = curses.textpad.Textbox(nw)
    if deco=="frame":
        screen.attron(decoColorpair)
        curses.textpad.rectangle(screen,y-1,x-1,y+h,x+w)
        screen.attroff(decoColorpair)
    elif deco=="underline":
        screen.hline(y+1,x,underlineChr,w,decoColorpair)

    nw.addstr(0,0,value,textColorpair)
    nw.attron(textColorpair)
    screen.refresh()
    return txtbox

To use it just do:要使用它,只需执行以下操作:

foo = maketextbox(1,40, 10,20,"foo",deco="underline",textColorpair=curses.color_pair(0),decoColorpair=curses.color_pair(1))
text = foo.edit()

textpad.Textbox(win, insert_mode=True) provides basic insert support. textpad.Textbox(win, insert_mode=True)提供基本的插入支持。 Backspace needs to be added though.但是需要添加退格键。

The initial code didn't work, decided to have a hack at it, this works on insert mode and then when you press Ctrl-G display's the text at the right position.最初的代码不起作用,决定对其进行破解,这适用于插入模式,然后当您按 Ctrl-G 时,将文本显示在正确的位置。

import curses
import curses.textpad

def main(stdscr):
    stdscr.clear()
    stdscr.refresh()
    win = curses.newwin(5, 60, 5, 10)

    tb = curses.textpad.Textbox(win, insert_mode=True)
    text = tb.edit()
    curses.flash()
    win.clear()
    win.addstr(0, 0, text.encode('utf-8'))
    win.refresh()
    win.getch()

curses.wrapper(main)

I found that the Edit widget in the urwid package is sufficient for my needs.我发现urwid包中的Edit小部件足以满足我的需求。 This is not the Textpad widget, but something different.这不是 Textpad 小部件,而是不同的东西。 The urwid package is overall nicer, anyway.无论如何,urwid 包总体上更好。 However, it's still not pain-free.然而,它仍然不是无痛的。 The Edit widget does allow inserting text, but not overwriting (toggled with Ins key), but that's not a big deal. Edit小部件确实允许插入文本,但不允许覆盖(用 Ins 键切换),但这没什么大不了的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM