如何使用Python和curses Textbox小部件编辑文本?
有没有人能提供一个使用curses.textpad.Textbox小部件来编辑现有文本的有效示例?当然,这是在Linux终端中进行的(比如xterm)。
4 个回答
6
textpad.Textbox(win, insert_mode=True)
这个代码可以让你在窗口中插入文本,基本的插入功能是有的。不过,删除功能(比如按退格键)还需要自己添加。
9
我花了几分钟在那儿找到了这个。
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'))
我还写了一个函数来创建一个文本框:
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
使用它只需要这样做:
foo = maketextbox(1,40, 10,20,"foo",deco="underline",textColorpair=curses.color_pair(0),decoColorpair=curses.color_pair(1))
text = foo.edit()
3
我发现Edit
这个小工具在urwid这个包里已经能满足我的需求了。它不是Textpad这个小工具,而是另一个东西。总的来说,urwid这个包更好用。不过,它还是有点小麻烦。这个Edit
小工具可以插入文字,但不能覆盖已有的文字(可以用Ins键切换),不过这也不是太大的问题。