为什么我不能在Python curses窗口的最后一行/列使用addstr()?

8 投票
2 回答
5188 浏览
提问于 2025-04-17 22:40

我在用Python写程序,想把光标的位置写到我的curses窗口的右下角,使用的是addstr()这个函数,但出现了错误。ScreenH-2可以正常工作,不过它是在窗口底部上面第二行显示的。ScreenH-1根本不行。我到底哪里搞错了呢?

import curses

ScreenH = 0
ScreenW = 0
CursorX = 1
CursorY = 1

def repaint(screen):   
   global ScreenH
   global ScreenW
   global CursorX
   global CursorY

   ScreenH, ScreenW = screen.getmaxyx()
   cloc = '   ' + str(CursorX) + ':' + str(CursorY) + ' '
   cloclen =  len (cloc)
   screen.addstr (ScreenH - 1, ScreenW - cloclen, cloc,  curses.color_pair(1));


def Main(screen):
   curses.init_pair (1, curses.COLOR_WHITE, curses.COLOR_BLUE)
   repaint (screen)   

   while True:
      ch = screen.getch()
      if ch == ord('q'):
         break

      repaint (screen)     


curses.wrapper(Main)

  File "test.py", line 17, in repaint
    screen.addstr (ScreenH - 1, ScreenW - cloclen, cloc,  curses.color_pair(1));
_curses.error: addstr() returned ERR

2 个回答

19

你也可以用 insstr 来代替 addstr

screen.insstr(ScreenH - 1, ScreenW - 1 - cloclen, cloc,  curses.color_pair(1))

这样做可以防止滚动,从而让你可以在最后一行的最后一个字符之前打印内容。

1

你需要像处理高度一样,从宽度中减去1。否则,字符串会超出屏幕的宽度。

screen.addstr(ScreenH - 1, ScreenW - 1 - cloclen, cloc,  curses.color_pair(1))
                                   ^^^

撰写回答