如何在 Python 中检测 window 调整大小

How to detect window resize in Python

如何查看 window 是否已调整大小?我以全屏模式开始,但如果我改变它以适合我的一半屏幕,我所有的文字都会混淆。

这是我的代码:

# Import os
import os

# Create function called title that prints the title screen
def title():
    print('@------------------------------------------------------------------------------------@'.center(os.get_terminal_size().columns), end='')
    print('|                                                                                    |'.center(os.get_terminal_size().columns), end='')
    print('|                                      |PyTerm v0.1.7|                               |'.center(os.get_terminal_size().columns), end='')
    print('|                                                                                    |'.center(os.get_terminal_size().columns), end='')
    print('@------------------------------------------------------------------------------------@'.center(os.get_terminal_size().columns), end='')

# Call the function
title()

一旦我 运行 它,文本就会对齐,但是当我进入全屏时,它们会到处都是。有没有办法来解决这个问题?当用户调整 window 的大小时,我能以某种方式感知吗?我在 Windows 10,使用 Python 3.1.9。 运行 它与 py ( C:\Windows\py.exe )

这是我 运行 时的样子:

这是我进入全屏时的样子:

谢谢

我没有 Windows 机器可以测试,但一种可能是循环重绘控制台:

  1. 清除当前屏幕(参见:Clear terminal in Python
  2. 运行 title 函数
  3. 稍等片刻

如果用户调整屏幕大小,offset 变量的调整值应设置为新大小。

import os
import time


def title(offset_value):
    print('@------------------------------------------------------------------------------------@'.center(offset_value), end='')
    print('|                                                                                    |'.center(offset_value), end='')
    print('|                                      |PyTerm v0.1.7|                               |'.center(offset_value), end='')
    print('|                                                                                    |'.center(offset_value), end='')
    print('@------------------------------------------------------------------------------------@'.center(offset_value))


if __name__ == "__main__":

    while True:

        # Clear the terminal
        # See: 
        os.system('cls' if os.name == 'nt' else 'clear')

        # Redraw the screen
        offset = os.get_terminal_size().columns
        title(offset)

        # Wait for a bit
        time.sleep(1)