Python Curses Handling Window (Terminal) Resize

徘徊边缘 提交于 2019-12-03 04:38:07

Terminal resize event will result in the curses.KEY_RESIZE key code. Therefore you can handle terminal resize as part of a standard main loop in a curses program, waiting for input with getch.

jarsever

I got my python program to re-size the terminal by doing a couple of things.

# 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.

user3237013

It isn't right. It's an ncurses-only extension. The question asked about curses. To do this in a standards-conforming way you need to trap SIGWINCH yourself and arrange for the screen to be redrawn.

I use the code from here.

In my curses-script I don't use getch(), so I can't react to KEY_RESIZE.

Therefore the script reacts to SIGWINCH and within the handler re-inits the curses library. 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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!