如何使文本适合 python 诅咒文本框? [英] How to make text fit inside a python curses textbox?

查看:47
本文介绍了如何使文本适合 python 诅咒文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've tried many things attempting to make the text stay inside its borders but I can't find a way. Below is what I've already tried.

#!/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()

推荐答案

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

Your first problem is that calling box1.box() takes up space in your box. It uses up the top row, the bottom row, the first column, and the last column. When you use box1.addstr() to put a string in a box, it starts at col 0, row 0, and so overwrites the box characters. After creating your borders, your box only has 38 available characters per line.

我不是一个诅咒专家,但解决这个问题的一种方法是创建一个新的盒子inside box1,它一直被一个字符插入.即:

I'm not a curses expert, but one way of resolving this is to create a new box inside box1 that is inset by one character all the way around. That is:

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

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

Then you can write your text into that box without overwriting the box drawing characters in box1. It's also not necessary to call textwrap.fill; it appears that writing a string to a window with addstr automatically wraps the text. In fact, calling textwrap.fill can interact badly with the window: if text wrap breaks a line at exactly the window width, you may end up with an erroneous blank line in your output.

给定以下代码:

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()

我的输出如下所示:

这篇关于如何使文本适合 python 诅咒文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆