如何使文本适合 python 诅咒文本框?

ans*_*ker 2 python curses ncurses

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

#!/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()
Run Code Online (Sandbox Code Playgroud)

lar*_*sks 6

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

我不是诅咒专家,但解决这个问题的一种方法是在里面 创建一个新的盒子box1它一直被一个角色插入。那是:

box2 = curses.newwin(18,38,7,51)
Run Code Online (Sandbox Code Playgroud)

然后,您可以将文本写入该框中,而无需覆盖box1. 也没有必要打电话textwrap.fill; 似乎将字符串写入窗口并addstr自动换行文本。事实上,调用textwrap.fill可能会与窗口发生严重的交互:如果文本换行在恰好窗口宽度处换行,则最终可能会在输出中出现错误的空行。

鉴于以下代码:

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()
Run Code Online (Sandbox Code Playgroud)

我的输出如下所示:

在此处输入图片说明


Tho*_*key 5

window 的一部分,并使用与文本相同的不动产。在第一个窗口上绘制一个框后,您可以制作第一个窗口的子窗口。然后在子窗口中写入您的包装文本。

就像是

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))
Run Code Online (Sandbox Code Playgroud)

请参阅derwin参考资料中的说明。