pygame.error.错误:文本宽度为零;有什么更好的方法使其工作?

2024-10-03 00:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个完全基于GUI的文本冒险(有一些显示文本的框以及可以单击以移动和攻击的按钮)。我在展示我的盒子时有点麻烦 以下是有问题的代码行:

下一个文件中导入的相关变量:

textWhite = (240, 234, 214)

错误发生的地方

^{pr2}$

执行上述代码的截断版本(无游戏循环):

class screenDisplay():
    def __init__(self):
        self.state = "TITLE_SCREEN"
        self.states = ["TITLE_SCREEN", "MAIN_GAME", "COMBAT", "CUTSCENE"]
        if self.state == self.states[0]:
            self.showTitleScreen()
def showTitleScreen(self):
        #Background
        background = Banner(scrW//2, scrH//2, scrW, scrH, avocado, "  ", 2)
        background.display()

在第四个.py文件中,是执行上述操作的游戏循环:

import pygame
import time
from screenDisplay import screenDisplay
import globalvars

# pylint: disable=no-member 
pygame.init() 
# pylint: enable=no-member
clock = pygame.time.Clock()
showGame = screenDisplay()

while not globalvars.gameIsDone:
    for event in pygame.event.get():
        # pylint: disable=no-member 
        if event.type == pygame.QUIT:
            done = True
            pygame.quit() 
            # pylint: enable=no-member
    pygame.display.update()
    clock.tick(30)

我已经读过this问题,但我不知道我应该把del行放在哪里,甚至不知道应该删除什么。如果解决方案涉及将这两行放在同一个文件中,是否有其他选择?在

编辑:哦,最重要的是,这是错误!在

Traceback (most recent call last):
  File "c:\Users\Robertson\Desktop\Personal Projects\pytextrpg\gameLauncher.py", line 9, in <module>
    showGame = screenDisplay()
  File "c:\Users\Robertson\Desktop\Personal Projects\pytextrpg\screenDisplay.py", line 9, in __init__
    self.showTitleScreen()
  File "c:\Users\Robertson\Desktop\Personal Projects\pytextrpg\screenDisplay.py", line 26, in showTitleScreen
    background.display()
  File "c:\Users\Robertson\Desktop\Personal Projects\pytextrpg\Banner.py", line 19, in display
    surface = self.textObject.render(self.text, True, textWhite)
pygame.error: Text has zero width

Tags: noinpyimportselfdisplaypygameusers
2条回答

不要在事件循环中执行pygame.quit()。请注意您如何在它之后执行display.update。退出循环后,作为最后一件事退出。在

pygame.init()

done = False
while not done and ...:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      done = True
      break # Other events became irrelevant.
  pygame.display.update()
  clock.tick(30)

# Now that we're done:
pygame.quit()

pygame.quit()不退出程序-它只退出/关闭pygame-这意味着它从内存中删除pygame的元素。在

但关闭pygame之后,它仍然执行pygame.display.update(),这就造成了问题。在

所以您需要exit()sys.exit()pygame.quit()之后立即退出程序。在

 if event.type == pygame.QUIT:
     pygame.quit() 
     exit() 
     #sys.exit()

或者您应该离开while循环-使用globalvars.gameIsDone = True而不是done = True,然后使用pygame.quit()-类似于@9000答案。在

^{pr2}$

相关问题 更多 >