[英]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.