Python Curses处理窗口(终端)调整大小

Pez*_*kow 23 python curses resize

这真是两个问题:

  • 如何调整curses窗口的大小,以及
  • 如何在curses中处理终端调整大小?

是否有可能知道窗口何时改变了大小?

我真的找不到任何好的文档,甚至没有在http://docs.python.org/library/curses.html上找到

Mic*_*lin 24

终端调整大小事件将导致curses.KEY_RESIZE密钥代码.因此,您可以将终端调整大小作为curses程序中标准主循环的一部分来处理,等待输入getch.

  • 这是正确的,但仅当 ncurses 使用 --enable-sigwinch 编译时。特别是,Debian 和 Ubuntu 中的 libncurses 没有打开该功能;我不知道为什么。 (2认同)

jar*_*ver 8

我得到了我的python程序,通过做一些事情来重新调整终端的大小.

# Initialize the screen
import curses

screen = curses.initscr()

# Check if screen was re-sized (True or False)
resize = curses.is_term_resized(y, x)

# Action in loop if resize is True:
if resize is True:
    y, x = screen.getmaxyx()
    screen.clear()
    curses.resizeterm(y, x)
    screen.refresh()
Run Code Online (Sandbox Code Playgroud)

当我正在编写我的程序时,我可以看到将我的屏幕放入其自己的类中的有用性,所有这些函数都已定义,所以我所要做的就是调用Screen.resize()它,它会处理剩下的事情.

  • 在 `resize = curses.is_term_resized(y, x)` 中,您在哪里取 `y, x` ?是旧尺寸吗?如果是这样,如何获得终端尺寸?对我来说,“screen.getmaxyx()”似乎没有返回更新后的大小。当我改变命令行的大小时,它仍然是一样的...... (4认同)

Jac*_*eur 5

我使用这里的代码。

在我的curses脚本中,我不使用getch(),所以我无法对KEY_RESIZE.

因此,脚本会做出反应SIGWINCH并在处理程序中重新初始化curses 库。当然,这意味着您必须重新绘制所有内容,但我找不到更好的解决方案。

一些示例代码:

from curses import initscr, endwin
from signal import signal, SIGWINCH
from time import sleep

stdscr = initscr()

def redraw_stdscreen():
    rows, cols = stdscr.getmaxyx()
    stdscr.clear()
    stdscr.border()
    stdscr.hline(2, 1, '_', cols-2)
    stdscr.refresh()

def resize_handler(signum, frame):
    endwin()  # This could lead to crashes according to below comment
    stdscr.refresh()
    redraw_stdscreen()

signal(SIGWINCH, resize_handler)

initscr()

try:
    redraw_stdscreen()

    while 1:
        # print stuff with curses
        sleep(1)
except (KeyboardInterrupt, SystemExit):
    pass
except Exception as e:
    pass

endwin()
Run Code Online (Sandbox Code Playgroud)