在 python curses 中不断更新字符串

Continuously update string in python curses

为了学习 curses,我写了这个脚本让用户输入两个数字,然后输出它们的和和差:

import curses

screen = curses.initscr()
screen.refresh()

height = 4
width = 25
abwindow =  curses.newwin(height, width, int(0.15*int(curses.LINES)), int(curses.COLS/2) - width)
abwindow.addstr(1, 2, "a is : ")
abwindow.addstr(2, 2, "b is : ")

abwindow.border()
abwindow.refresh()

sumdiffwindow = curses.newwin(height, width, int(0.15*int(curses.LINES)), int(curses.COLS/2))
sumdiffwindow.addstr(1, 2, "a + b is : ")
sumdiffwindow.addstr(2, 2, "a - b is : ")

sumdiffwindow.border()
sumdiffwindow.refresh()

atocheck = abwindow.getstr(1, 10, 7)
btocheck = abwindow.getstr(2, 10, 7)

try:
    a = float(atocheck)
    b = float(btocheck)
    sum = a + b
    diff = a - b
    sumdiffwindow.addstr(1, 14, "%g" %(sum))
    sumdiffwindow.addstr(2, 14, "%g" %(diff))
except ValueError:
    sumdiffwindow.addstr(1, 14, "nan")
    sumdiffwindow.addstr(2, 14, "nan")

sumdiffwindow.refresh()
curses.curs_set(0)

while True:
    curses.noecho()
    c = screen.getch(1, 1)
    if c == ord('q') or c == ord('Q'):
        break

curses.endwin()

输入两个数字后,(如果是数字)计算和差,然后空闲,直到用户按'q'返回终端。我该如何更改它以便我可以根据需要更新 ab(使用键盘向上和向下箭头在两个输入框之间导航),同时不断显示它们的当前总和和区别?

您可以将 window 超时设置为较小的值,例如 10(毫秒)。如果您使用 nodelay,它将无法与箭头键一起使用。

这样做会使 getch return(可能有错误...)在短时间后。完成后,更新屏幕的其他部分,然后返回,要求 getch 输入直到 return 是有效的东西(例如向上箭头键)。

我也是 curses 的新手,但我尽力帮助了你。 显示结果后,如果按除q以外的任意键,都将像biginning一样更新。但是如果你按下q,代码就会退出。

import curses
import time
import sys

def main():
    screen = curses.initscr()
    screen.refresh()
    height = 4
    width = 25
    abwindow =  curses.newwin(height, width, int(0.15*int(curses.LINES)), int(curses.COLS/2) - width)
    abwindow.addstr(1, 2, "a is : ")
    abwindow.addstr(2, 2, "b is : ")

    abwindow.border()
    abwindow.refresh()

    sumdiffwindow = curses.newwin(height, width, int(0.15*int(curses.LINES)), int(curses.COLS/2))
    sumdiffwindow.addstr(1, 2, "a + b is : ")
    sumdiffwindow.addstr(2, 2, "a - b is : ")

    sumdiffwindow.border()
    sumdiffwindow.refresh()
    curses.echo()
    atocheck = abwindow.getstr(1, 10, 7)
    btocheck = abwindow.getstr(2, 10, 7)

    try:
        a = float(atocheck)
        b = float(btocheck)
        sum = a + b
        diff = a - b
        sumdiffwindow.addstr(1, 14, "%g" %(sum))
        sumdiffwindow.addstr(2, 14, "%g" %(diff))
    except ValueError:
        sumdiffwindow.addstr(1, 14, "nan")
        sumdiffwindow.addstr(2, 14, "nan")
    sumdiffwindow.refresh()
    curses.curs_set(0)
    curses.noecho()
    c = screen.getch(1, 1)
    if c == ord('q') or c == ord('Q'):
        sys.exit()


while True:
    main()