Python Curses Handling Window (Terminal) Resize

2019-03-24 06:51发布

问题:

This is two questions really:

  • how do I resize a curses window, and
  • how do I deal with a terminal resize in curses?

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

回答1:

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.



回答2:

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.



回答3:

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.