Python 3.x 如何在pygame屏幕上显示txt文件?

Python 3.x 如何在pygame屏幕上显示txt文件?,python-3.x,text,pygame,pong,Python 3.x,Text,Pygame,Pong,我想知道是否有可能在pygame屏幕上显示txt文件中的文本。我正在制作一个游戏,我试图在游戏中显示文本文件中的指令 以下是我所做的: def instructions(): instructText = instructionsFont.render(gameInstructions.txt, True, WHITE) screen.blit(instructText, ((400 - (instructText.get_width()/2)),(300 - (instruct

我想知道是否有可能在pygame屏幕上显示txt文件中的文本。我正在制作一个游戏,我试图在游戏中显示文本文件中的指令

以下是我所做的:

def instructions():
    instructText = instructionsFont.render(gameInstructions.txt, True, WHITE)
    screen.blit(instructText, ((400 - (instructText.get_width()/2)),(300 - (instructText.get_height()/2))))
但是我得到了一个错误:

line 356, in instructions
    instructText = instructionsFont.render(pongInstructions.txt, True, WHITE)
NameError: name 'pongInstructions' is not defined

然而,我的尝试完全是尝试和错误,因为我实际上不确定如何做到这一点。。。非常感谢您的帮助

gameinstructions
没有定义,因为python认为它是一个变量

要告诉python它是一个字符串,您需要将它放在引号中:

instructText = instructionsFont.render("gameInstructions.txt", True, WHITE)
然而,这可能不是你想要的。您要做的是读取文件。为此,应使用
with
语句安全地打开和关闭文件:

with open("gameInstructions.txt") as f:
    instructText = instructionsFont.render(f.read(), True, WHITE)
我目前无法尝试该代码,但如果pygame无法同时处理多行文本,您可能需要遍历这些行:

with open("gameInstructions.txt") as f:
    for line in f:
        instructText = instructionsFont.render(line, True, WHITE)

gameinstructions
没有定义,因为python认为它是一个变量

要告诉python它是一个字符串,您需要将它放在引号中:

instructText = instructionsFont.render("gameInstructions.txt", True, WHITE)
然而,这可能不是你想要的。您要做的是读取文件。为此,应使用
with
语句安全地打开和关闭文件:

with open("gameInstructions.txt") as f:
    instructText = instructionsFont.render(f.read(), True, WHITE)
我目前无法尝试该代码,但如果pygame无法同时处理多行文本,您可能需要遍历这些行:

with open("gameInstructions.txt") as f:
    for line in f:
        instructText = instructionsFont.render(line, True, WHITE)

我尝试了这段代码,但是我得到了一个错误:第26行,在decode return codecs.ascii_decode(input,self.errors)[0]UnicodeDecodeError:“ascii”编解码器无法解码397位的字节0xe2:序号不在范围内(128)您使用的python版本是什么?它似乎期望ascii,而“–”字符不是其中的一部分。从其他帖子中,我可以看到它应该支持unicode,我在Python3.6.0中运行它,这通常是由错误的区域设置引起的。尝试使用
open(filename,encoding='utf-8')
强制对文件进行编码,或者检查您的区域设置是否正确。其他相关问题:我尝试了此代码,但遇到一个错误,即:decode return codecs.ascii\u decode(input,self.errors)[0]UnicodeDecodeError:“ascii”编解码器无法解码第397位的字节0xe2:序号不在范围内(128)您使用的是哪一版本的python?它似乎期望ascii,而“–”字符不是其中的一部分。从其他帖子中,我可以看到它应该支持unicode,我在Python3.6.0中运行它,这通常是由错误的区域设置引起的。请尝试使用
打开(filename,encoding='utf-8')
强制对文件进行编码,或检查您的区域设置是否正确。其他相关问题: