Pygame 屏幕在一次呈现文本一个字符的函数中间冻结
Pygame screen freezes in the middle of a function that renders text one character at a time
我是 Stack Overflow 以及 pygame 和 python 的新手,所以如果我犯了一个非常简单的错误,请原谅我。我试图在 pygame 屏幕中一次显示一个字符的文本。我的函数工作正常,呈现我想要的效果,除了它随机冻结,在标题区域显示 "Not Responding",在不一致的时间(例如,有时它会在呈现 10 个字母后冻结,有时在 28 个字母后冻结,等等)。即使在我重新启动计算机后也会发生这种情况。我的问题是:这只是发生在我身上,还是我的代码有问题,如果我的代码有问题,请帮助我修复它。这是我的代码,提前谢谢你:
import pygame, time
from pygame.locals import *
width = 800
height = 800
pygame.init()
scrn = pygame.display.set_mode((width, height))
font = pygame.font.SysFont(None, 22)
def render_text(string, bg = None, text_color = (0, 0, 0), surf = scrn, width = width, height = height):
text = ''
for i in range(len(string)):
if bg == None:
surf.fill((255, 255, 255))
else:
surf.blit(bg, (0, 0))
text += string[i]
text_surface = font.render(text, True, text_color)
text_rect = text_surface.get_rect()
text_rect.center = (width/2, height/2)
surf.blit(text_surface, text_rect)
pygame.display.update()
time.sleep(0.05)
def intro():
while True: #just used as an example, it will freeze up usually sometime during the first or second iteration
render_text("It was a dark and stormy night.")
time.sleep(2)
intro()
Pygame 不使用事件队列的程序应该在每次迭代时调用 pygame.event.pump。这将防止发生冻结。将 intro
函数更改为如下所示应该有效:
def intro():
while True:
pygame.event.pump()
render_text("It was a dark and stormy night.")
time.sleep(2)
我是 Stack Overflow 以及 pygame 和 python 的新手,所以如果我犯了一个非常简单的错误,请原谅我。我试图在 pygame 屏幕中一次显示一个字符的文本。我的函数工作正常,呈现我想要的效果,除了它随机冻结,在标题区域显示 "Not Responding",在不一致的时间(例如,有时它会在呈现 10 个字母后冻结,有时在 28 个字母后冻结,等等)。即使在我重新启动计算机后也会发生这种情况。我的问题是:这只是发生在我身上,还是我的代码有问题,如果我的代码有问题,请帮助我修复它。这是我的代码,提前谢谢你:
import pygame, time
from pygame.locals import *
width = 800
height = 800
pygame.init()
scrn = pygame.display.set_mode((width, height))
font = pygame.font.SysFont(None, 22)
def render_text(string, bg = None, text_color = (0, 0, 0), surf = scrn, width = width, height = height):
text = ''
for i in range(len(string)):
if bg == None:
surf.fill((255, 255, 255))
else:
surf.blit(bg, (0, 0))
text += string[i]
text_surface = font.render(text, True, text_color)
text_rect = text_surface.get_rect()
text_rect.center = (width/2, height/2)
surf.blit(text_surface, text_rect)
pygame.display.update()
time.sleep(0.05)
def intro():
while True: #just used as an example, it will freeze up usually sometime during the first or second iteration
render_text("It was a dark and stormy night.")
time.sleep(2)
intro()
Pygame 不使用事件队列的程序应该在每次迭代时调用 pygame.event.pump。这将防止发生冻结。将 intro
函数更改为如下所示应该有效:
def intro():
while True:
pygame.event.pump()
render_text("It was a dark and stormy night.")
time.sleep(2)