[英]Edit text using Python and curses Textbox widget?
有没有人有使用 curses.textpad.Textbox 小部件编辑现有文本的工作示例? 当然,这是在 Linux 终端(例如 xterm)中。
发现这个有几分钟
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()
textpad.Textbox(win, insert_mode=True)
提供基本的插入支持。 但是需要添加退格键。
最初的代码不起作用,决定对其进行破解,这适用于插入模式,然后当您按 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)
我发现urwid包中的Edit
小部件足以满足我的需求。 这不是 Textpad 小部件,而是不同的东西。 无论如何,urwid 包总体上更好。 然而,它仍然不是无痛的。 Edit
小部件确实允许插入文本,但不允许覆盖(用 Ins 键切换),但这没什么大不了的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.