如何使文本适合 python curses 文本框?

How to make text fit inside a python curses textbox?

我尝试了很多方法试图使文本保持在其边界内,但我找不到方法。以下是我已经尝试过的方法。

#!/usr/bin/env python

import curses
import textwrap

screen = curses.initscr()
screen.immedok(True)

try:
    screen.border(0)

    box1 = curses.newwin(20, 40, 6, 50)
    box1.immedok(True)
    text = "I want all of this text to stay inside its box. Why does it keep going outside its borders?"
    box1.box()
    box1.addstr(1, 0, textwrap.fill(text, 39))

    #box1.addstr("Hello World of Curses!")

    screen.getch()

finally:
    curses.endwin()

window 的一部分,并使用与文本相同的空间。您可以在第一个 window 上绘制一个框后,为第一个 window 创建一个子 window。然后在 subwindow.

中写下你的换行文字

类似

box1 = curses.newwin(20, 40, 6, 50)
box1.immedok(True)
text = "I want all of this text to stay inside its box. Why does it keep going outside its borders?"
box1.box()
box1.refresh()
# derwin is relative to the parent window:
box2 = box1.derwin(18, 38, 1,1)
box2.addstr(1, 0, textwrap.fill(text, 39))

参见参考文献中 derwin 的描述。

你的第一个问题是调用 box1.box() 在你的盒子里占用了 space。它用完顶行、底行、第一列和最后一列。当您使用 box1.addstr() 将字符串放入框中时,它从第 0 列、第 0 行开始,因此会覆盖框字符。创建边框后,您的框每行只有 38 个可用字符。

我不是 curses 专家,但解决这个问题的一种方法是创建一个新框 inside box1 一直插入一个字符大约。即:

box2 = curses.newwin(18,38,7,51)

然后您可以将文本写入该框而不会覆盖 box1 中的框绘图字符。也没有必要调用 textwrap.fill;似乎用 addstr 将字符串写入 window 会自动换行文本。事实上,调用 textwrap.fill 可能会与 window 交互不良:如果文本换行恰好在 window 宽度处换行,您可能会在输出中出现错误的空行。

给定以下代码:

try:
    screen.border(0)

    box1 = curses.newwin(20, 40, 6, 50)
    box2 = curses.newwin(18,38,7,51)
    box1.immedok(True)
    box2.immedok(True)
    text = "I want all of this text to stay inside its box. Why does it keep going outside its borders?"
    text = "The quick brown fox jumped over the lazy dog."
    text = "A long time ago, in a galaxy far, far away, there lived a young man named Luke Skywalker."
    box1.box()
    box2.addstr(1, 0, textwrap.fill(text, 38))

    #box1.addstr("Hello World of Curses!")

    screen.getch()

finally:
    curses.endwin()

我的输出如下所示: