【发布时间】:2017-01-19 11:43:31
【问题描述】:
我正在使用 pygame 开发一个简单的 GUI。在某些时候,由于制表符和空格的混合,我厌倦了不断出现的缩进错误,因此我决定使用 vi 将所有制表符替换为 4 个空格。之后我得到一些关于 pygame.font.SysFont 没有被初始化的错误,即使它是之前的。 当然,我认为这与我只是将制表符更改为空格有关,因此我确保所有内容都正确缩进等。我注释掉了 95% 的代码并开始与旧版本的代码进行比较,从旧版本中复制行代码到新的。因为它们似乎是相同的(使用 cat -A file.py 来比较不可见的字符)。
我终于发现这是罪魁祸首: trouble-maker
这是两个文件之间唯一不同的地方(不在三引号中)。将此行更改为具有选项卡确实可以解决问题。 所以,我想问题解决了。
我的问题是: 这怎么可能?空格不应该比制表符更不容易出错吗?
代码如下:
import pygame
pygame.init()
class GameMenu():
def __init__(self, screen, items, bg_color=(237,237,223), font="Verdana", font_size=30,
font_color=(237, 28, 36)):
self.screen = screen
self.scr_width = self.screen.get_rect().width
self.scr_height = self.screen.get_rect().height
self.bg_color = bg_color
self.clock = pygame.time.Clock()
self.items = items
self.font = pygame.font.SysFont(font, font_size)
self.font_color = font_color
"""
rest of the code commented out
"""
pygame.quit()
if __name__ == "__main__":
screensize = 0
screen = pygame.display.set_mode((640, 480), screensize, 32)
menu_items = ('1', '2', '3', '4', '5')
pygame.display.set_caption('numbers')
pygame.mouse.set_visible(True)
gm = GameMenu(screen, menu_items)
我在这里缺少什么?为什么前面 pygame.quit() 的选项卡可以工作,但没有 4 个空格会给出“pygame.error:字体未初始化”
编辑:这是回溯
Traceback (most recent call last):
File "testMenu.py", line 168, in <module>
gm = GameMenu(screen, menu_items)
File "testMenu.py", line 31, in __init__
self.font = pygame.font.SysFont(font, font_size)
File "/usr/lib/python2.7/dist-packages/pygame/sysfont.py",
line 614, in SysFont
return constructor(fontname, size, set_bold,
set_italic)
File
"/usr/lib/python2.7/dist-packages/pygame/sysfont.py", line 537, in font_constructor
font = pygame.font.Font(fontpath, size)
pygame.error: font not initialized
另请注意,pygame.font.init() 不是必需的,请参阅https://www.pygame.org/docs/tut/ImportInit.html
【问题讨论】:
-
能否提供回溯等? (解释器显示的输出)。
-
pygame.quit()应该在__init__方法中吗? FWIW,Python 使用大小为 8 的固定制表位。 -
具体细节请看The Python Language Reference的词法分析部分Indentation的第二段
-
@PM2Ring 它不应该在
__init__方法中,它应该在 GameMenu 类的末尾。有趣的是,你和 wildwilhelm 提出了 8 个空格,因为这与 pep-8