简体   繁体   English

Python:使用curses库打印ASCII文本文件

[英]Python: Printing ASCII text file using curses library

I'm trying to print a text file that contains ASCII art in python.我正在尝试在 python 中打印包含 ASCII 艺术的文本文件。

I realize the easy way would be do something like this我意识到简单的方法是做这样的事情

with open(image, 'r') as f:
for line in f:
    print(line.rstrip())

but I want to print it using the curses library so that I can display other text along with the image.但我想使用 curses 库打印它,以便我可以显示其他文本以及图像。 Here is what I've come up with so far.到目前为止,这是我想出的。

lines=[]
with open('image.txt',"r",encoding="utf8") as f:
        lines.append(f.readlines())

for a in lines:
    char = str(("".join(a)))
    stdscr.addstr(y, x, char)

This code does 90% of the job but I cant get the image to shift to the right.这段代码完成了 90% 的工作,但我无法让图像向右移动。 I can choose which row the image begins on by changing the y in stdscr.addstr(y, x, char) but changing x has no effect on which column it starts in.我可以通过更改 stdscr.addstr(y, x, char) 中的 y 来选择图像从哪一行开始,但更改 x 对它从哪一列开始没有影响。

Is there a way to fix this?有没有办法来解决这个问题? Thanks.谢谢。

When you call lines.append() , you're taking the entire list returned by f.readlines() , and adding it to lines as a single item.当您调用lines.append()时,您将获取f.readlines()返回的整个列表,并将其作为单个项目添加到lines中。 for a in lines , then, loops only once, joining the elements of a (the entire file) back together and passing that to addstr() , which interprets the embedded line feeds, resetting each line after the first to the first column.然后for a in lines只循环一次,将a (整个文件)的元素重新连接在一起并将其传递给addstr() ,它解释嵌入的换行符,将第一行之后的每一行重置为第一列。

Instead of lines.append() , you either want lines.extend() , or, more likely, just lines = f.readlines() .而不是lines.append() ,您要么需要lines.extend() ,或者更有可能只lines = f.readlines() You can then dispense with the join, although you should probably strip the line feeds.然后您可以省去连接,尽管您可能应该去除换行符。 Eg:例如:

with open('image.txt',"r",encoding="utf8") as f:
    lines = f.readlines()

for a in lines:
    # set x and y here
    stdscr.addstr(y, x, a.rstrip())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM