Python/Pygame-if语句对.txt文件有问题

Python/Pygame-if语句对.txt文件有问题,python,if-statement,pygame,Python,If Statement,Pygame,我有一个if语句,它检查.txt文件的某一行是否为==“true”,但它似乎工作不正常。。在这里: configfile=open("FirstGameConfig.txt") config_lines=configfile.readlines() speed_of_object=float(config_lines[5]) acceleration_of_object=float(config_lines[7]) show_coordinates=str(config_lines[9]) ##

我有一个if语句,它检查.txt文件的某一行是否为==“true”,但它似乎工作不正常。。在这里:

configfile=open("FirstGameConfig.txt")
config_lines=configfile.readlines()
speed_of_object=float(config_lines[5])
acceleration_of_object=float(config_lines[7])
show_coordinates=str(config_lines[9]) #####
acceleration_mode=str(config_lines[11])
configfile.close()
这一切都在上面,下面的show_坐标字符串似乎有问题:

font=pygame.font.Font(None, 40)
    if acceleration_mode=="true":
        speedblit=font.render("Speed:", True, activeblitcolor)
        screen.blit(speedblit, [0, 0])
        rectyspeedtext=font.render(str(abs(rectyspeed)), True, activeblitcolor)
        screen.blit(rectyspeedtext, [100, 0])
    if show_coordinates=="true":
        rectycoord=font.render(str(recty), True, activeblitcolor)
        screen.blit(rectycoord, [360, 570])
        rectxcoord=font.render(str(rectx), True, activeblitcolor)
        screen.blit(rectxcoord, [217, 570])
        coordblit=font.render("Coordinates: x=              y=", True, activeblitcolor)
        screen.blit(coordblit, [0, 570])
该脚本检查加速模式是否已打开。如果加速度模式的值为真,则对象的速度将打印在屏幕的左上角。activeblitcolor已经定义,所以这没有问题。 if show_coordinates语句下面的内容将在屏幕的左下角打印对象的坐标,假设我拥有的.txt文件中的值为“true”

所以问题是,即使在.txt文件中将show_坐标设置为true,也会跳过此语句。加速模式也在.txt文件中,它工作得非常好。如果检查加速度模式是否为true的语句工作正常,为什么show\u坐标的语句工作不一样?如果我删除了If语句,但在脚本中保留了它下面的代码,那么坐标确实会打印在屏幕的左下角,就像它们应该显示为If show_coordinates==“true”一样


我肯定在.txt文件的正确行上有“true”。如果我添加“print(show_坐标)”,那么“true”就是输出。脚本识别show_坐标的值为真,但if语句不识别?任何帮助都将不胜感激!我是初学者。

readlines方法将换行保留在行尾。我怀疑您的文件结尾没有换行符,而加速模式是最后一行,这就是为什么它可以工作的原因

为了证实我的怀疑,加上

print(repr(show_coordinates))
甚至

print(config_lines)
您可能会看到
show\u坐标
看起来像
'true\n'

要解决此问题,可以添加对
strip()
的调用以清理字符串。例如:

show_coordinates = config_lines[9].strip()
acceleration_mode = config_lines[11].strip()

如果您发布txt文件会有所帮助。您可以在终端上运行此文件并粘贴“打印(显示坐标)”的输出吗?既然你说输出是“真的”,我怀疑一个铸造错误正在发生