Python Curses 处理窗口(终端)调整大小
其实这是两个问题:
- 我该怎么调整curses窗口的大小?
- 在curses中,我该如何处理终端窗口大小的变化?
有没有办法知道一个窗口的大小什么时候发生了变化?
我真的找不到任何好的文档,连http://docs.python.org/library/curses.html上都没有提到。
5 个回答
5
我在这里使用了这段代码:这里。
在我的curses脚本中,我没有使用getch(),所以无法对KEY_RESIZE
做出反应。
因此,脚本会对
以下是一些示例代码:
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()
10
我让我的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()
在写这个程序的时候,我意识到把我的屏幕放到一个单独的类里是很有用的,这样我就可以把所有这些功能都定义在里面。这样我只需要调用一下 Screen.resize()
,程序就会自动处理其他的事情。
36
当终端窗口大小发生变化时,会产生一个叫做 curses.KEY_RESIZE
的按键代码。所以在使用 curses 这个库的程序中,你可以把终端大小变化的处理当作主循环的一部分,使用 getch
来等待用户输入。