如何正确刷新curses窗口?

20
while 1:
    ...
    window.addstr(0, 0, 'abcd')
    window.refresh()
    ...

window的大小等于终端的大小,足够大以容纳abcd。 如果将'abcd'修改为像'xyz'这样较短的字符串,那么在终端上我会看到'xyzd'。我到底做错了什么?

3个回答

17

假设您有这段代码,您只想知道如何实现draw()

def draw(window, string):
    window.addstr(0, 0, string)
    window.refresh()

draw(window, 'abcd')
draw(window, 'xyz')  # oops! prints "xyzd"!

最直接且类似于"curses"的解决方案无疑是

def draw(window, string):
    window.erase()  # erase the old contents of the window
    window.addstr(0, 0, string)
    window.refresh()
你可能会想写成这样:
def draw(window, string):
    window.clear()  # zap the whole screen
    window.addstr(0, 0, string)
    window.refresh()

但别用clear()!尽管名字看起来友好,它只是用来无条件地重绘整个屏幕,也就是所谓的“闪烁”。相比之下,erase() 函数可以在不闪烁的情况下做正确的事情。

Frédéric Hamidi提供以下方案,以擦除当前窗口的一部分或多部分:

def draw(window, string):
    window.addstr(0, 0, string)
    window.clrtoeol()  # clear the rest of the line
    window.refresh()

def draw(window, string):
    window.addstr(0, 0, string)
    window.clrtobot()  # clear the rest of the line AND the lines below this line
    window.refresh()

一个更短且纯Python的替代方案是

def draw(window, string):
    window.addstr(0, 0, '%-10s' % string)  # overwrite the old stuff with spaces
    window.refresh()

谢谢。我一直在思考如何消除闪烁,你的答案非常准确! - omsrisagar

9
addstr() 只会打印您指定的字符串,不会清除后面的字符。您需要自己处理:
  • 使用 clrtoeol() 清除直到该行末尾的所有字符,

  • 使用 clrtobot() 清除直到窗口底部的所有字符。


refresh() 之前和在 addstr() 之后(所有这些操作只会更新“虚拟”curses屏幕,直到调用refresh())。 - Frédéric Hamidi

1
我使用oScreen.erase()。它清除窗口并将光标放回0,0。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接