Pygame:无法将字体大小调整为窗口大小自定义功能工作



我是一个完全的初学者,我正在努力做到这一点:

pygame.init()
fps=60
FramePerSec=pygame.time.Clock()
WHITE=(255,255,255)
font = pygame.font.SysFont('comicsansms',20)

DISPLAYSURF=pygame.display.set_mode((640,480),pygame.RESIZABLE)
pygame.display.set_caption("3")
QUIT=pygame.QUIT
TIME=0
def adjustfontsize():
font=pygame.font.SysFont('comicsansms',int (min(DISPLAYSURF.get_width()/32,DISPLAYSURF.get_height()/24)))

nl=pygame.font.Font.get_linesize(font)*3/4
def writetext(x,y,n,z):DISPLAYSURF.blit(font.render(z,True,WHITE),(x,y+nl*(n-1)))
while True:
DISPLAYSURF.fill((0,0,0))
adjustfontsize()

for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
TIME=pygame.time.get_ticks()
if TIME>=2000:
writetext(DISPLAYSURF.get_width()/3,DISPLAYSURF.get_height()/4,1,"¡Hola! Soy la primer línea")
if TIME>=4000:
writetext(DISPLAYSURF.get_width()/3,DISPLAYSURF.get_height()/4,2,"¡Hola! Yo soy la segunda línea")
pygame.display.update()
FramePerSec.tick(fps)

现在,我想知道的是为什么字体大小仍然没有改变。已经添加了Lost Coder指出的缺失bg绘制,但这不是问题所在。我知道还有其他方法可以做到这一点,只是想通过了解我做错了什么来学习。建议的问题中没有类似的功能。非常感谢!

嘿,你需要将屏幕填充为黑色(在你的例子中,你使用的是黑色背景(,因为否则更新的文本将与其他文本重叠,并会导致渲染问题。

把屏幕想象成一幅油画画布,当你";draw";一幅新画你必须先把画布清理干净。这就是你对display.fill((0,0,0((的本质处理

如果您在相对调整大小方面仍然有问题,那么关于该主题的线程堆栈溢出已经存在。(如何根据显示器分辨率在pygame中缩放字体大小?(

更新:我已经测试过了,是的,问题似乎是你编辑了函数中的一个全局变量,但还没有返回;安全空间";您可以在函数中使用全局变量,但不能在全局空间中更改它们,除非您返回变量

def adjustfontsize():
font=pygame.font.SysFont('comicsansms',int (min(DISPLAYSURF.get_width()/32,DISPLAYSURF.get_height()/24)))
return font
#...
#...

while True:
font = adjustfontsize() #This will actually change the font in the global space.

(参考文献(https://www.geeksforgeeks.org/global-local-variables-python/

您也可以将函数中的变量定义为全局变量。但你不应该这样做,因为这是不好的做法。只需返回所需的变量。

def adjustFont():
global font
font = pygame.font.SysFont('comicsansms',int (min(DISPLAYSURF.get_width()/32,DISPLAYSURF.get_height()/24)))