如何键入变量并将其作为普通文本读取

2024-10-05 14:24:39 发布

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

如何键入变量并将其作为普通文本读取?你知道吗

例如

small_font = pie game.Font.System_Font('a type of font', 25)
size = 'small'
text_surface = size_font.render(text, True, color)

如何让我的计算机将大小_font.render.....读取为_font.render.....

摘要

我在上面有这些

smallfont = pygame.font.SysFont('comicsansms', 25) 
medimfont = pygame.font.SysFont('comicsansms', 50) 
largefont = pygame.font.SysFont('comicsansms', 80) 

我想要的是让我的电脑读取大小_字体.render..... 小的_字体.render..... 你知道吗


Tags: text文本gamesize键入字体rendersystem
2条回答

如果要根据字符串的值访问不同的变量/对象,标准解决方案是使用字典。例如:

fonts = {}
fonts['small'] = pygame.Font.System_Font('a type of font', 10)
fonts['normal'] = pygame.Font.System_Font('a type of font', 20)
fonts['big'] = pygame.Font.System_Font('a type of font', 40)
fonts['huge'] = pygame.Font.System_Font('a type of font', 80)

# and later, use these fonts with
text_surface = fonts['small'].render(text, True, color) # use size 10 font
# or
text_surface = fonts['huge'].render(text, True, color) # use size 80 font

编辑:也可以将字典键存储在变量中:

size = 'small'
text_surface = fonts[size].render(text, True, color) # use size 10 font
size = 'huge'
text_surface = fonts[size].render(text, True, color) # use size 80 font

将函数用作模块的属性:

import sys

small_font = pygame.font.SysFont('comicsansms', 25) 
size = 'small'
text_surface = getattr(sys.modules[__name__], "{0}_font".format(size)).render(text, True, color)

相关问题 更多 >