[英]Python Curses Handling Window (Terminal) Resize
This is two questions really:这真的是两个问题:
Is it possible to know when a window has changed size?是否有可能知道窗口何时改变了大小?
I really can't find any good doc, not even covered on http://docs.python.org/library/curses.html我真的找不到任何好的文档,甚至没有涵盖在http://docs.python.org/library/curses.html
Terminal resize event will result in the curses.KEY_RESIZE
key code.终端调整大小事件将导致
curses.KEY_RESIZE
键代码。 Therefore you can handle terminal resize as part of a standard main loop in a curses program, waiting for input with getch
.因此,您可以在 Curses 程序中将终端调整大小作为标准主循环的一部分处理,等待
getch
输入。
I got my python program to re-size the terminal by doing a couple of things.我让我的 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()
As I'm writing my program I can see the usefulness of putting my screen into it's own class with all of these functions defined so all I have to do is call Screen.resize()
and it would take care of the rest.在我编写程序时,我可以看到将我的屏幕放入它自己的类并定义所有这些函数的用处,所以我所要做的就是调用
Screen.resize()
并且它会处理其余的事情。
I use the code from here .我使用这里的代码。
In my curses-script I don't use getch(), so I can't react to KEY_RESIZE
.在我的 curses 脚本中,我不使用 getch(),所以我无法对
KEY_RESIZE
做出反应。
Therefore the script reacts to SIGWINCH
and within the handler re-inits the curses library.因此,脚本对
SIGWINCH
做出反应,并在处理程序中重新初始化 curses 库。 That means of course, you'll have to redraw everything, but I could not find a better solution.这当然意味着您必须重新绘制所有内容,但我找不到更好的解决方案。
Some example code:一些示例代码:
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()
This worked for me when using curses.wrapper() :这在使用curses.wrapper()时对我有用:
if stdscr.getch() == curses.KEY_RESIZE:
curses.resizeterm(*stdscr.getmaxyx())
stdscr.clear()
stdscr.refresh()
It isn't right.这是不对的。 It's an
ncurses-only
extension.这是一个
ncurses-only
扩展。 The question asked about curses
.这个问题是关于
curses
。 To do this in a standards-conforming way you need to trap SIGWINCH
yourself and arrange for the screen to be redrawn.要以符合标准的方式执行此操作,您需要自己捕获
SIGWINCH
并安排重新绘制屏幕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.