【问题标题】:how do I get a string to be recognised as my variable如何让字符串被识别为我的变量
【发布时间】:2015-08-02 09:57:21
【问题描述】:
import pygame
number=1
screen = pygame.display.set_mode((1920,1080))#,pygame.FULLSCREEN)
app1=pygame.image.load("moonlight.jpg").convert()
app2=pygame.image.load("youtube.jpg").convert()
clock = pygame.time.Clock()
while True:
    if number==1:
        screen.blit("app"+str(number), (-100,0))
    clock.tick(40)
    pygame.display.update()``

如何让"app"+str(number) 被识别为app1 变量。

我收到错误"argument 1 must be pygame.Surface, not str"

【问题讨论】:

  • 您需要按名称获取变量。你可以这样做:locals().get('app1', None)
  • 虽然可以使用包含变量名称的字符串来访问变量,但您想要这样做表明您应该使用字典而不是单独的变量。

标签: python-3.x pygame


【解决方案1】:

为了让您的生活更轻松,请尝试执行以下操作:

    while True:
        if number == 1:
            screen.blit(app1, (-100,0))
        elif number == 2:
            screen.blit(app2, (x coordinates, y coordinates))
        clock.tick(40)
        pygame.display.update()

这样,您就不必处理冲突的变量类型。同样使用这种方法,你的代码会变得更加紧凑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2023-01-15
    • 2022-06-16
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2017-02-12
    相关资源
    最近更新 更多