2017-08-13 68 views
0

我嘗試了很多事情,試圖讓文本留在它的邊界內,但我找不到方法。以下是我已經嘗試過的。如何使文本適合python curses文本框內?

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

回答

1

你的第一個問題是,調用box1.box()你的盒子佔用空間。它用盡了第一行,第一行,第一列和最後一列。當您使用box1.addstr()將一個字符串放入一個框中時,它會從第0列開始,並覆蓋該框字符。創建邊框後,您的盒子每行只有38個可用字符。

我不是一個詛咒專家,但是解決這個的一種方式是創建內部box1由一個字符的周圍插頁一路新盒子。那就是:

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

然後,你可以寫你的文字裝進盒子,但不覆蓋框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() 

我的輸出是這樣的:

enter image description here

+0

需要注意的是托馬斯·迪基和我已經基本張貼了同樣的答案,雖然他使用'.derwin'創建一個子窗口,這可能是更好的方法。我有圖片。拋硬幣 :) – larsks

2

窗口的一部分,並使用相同的房地產爲文本。在第一個窗口上繪製一個框後,您可以創建第一個窗口的子窗口。然後在子窗口中編寫包裝文本。

喜歡的東西

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描述。