首页 > 解决方案 > 如何键入变量并将其读取为普通文本

问题描述

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

例如

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) 

我想要的是让我的电脑读取 size_font.render ..... as small_font.render .....

标签: pythonvariables

解决方案


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

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

推荐阅读