在函数结束后将值保留在变量中导致 UnboundLocalError

问题描述

我正在尝试创建一个虚拟餐厅菜单,单击按钮会分配一个数字,该数字对应于我之前创建的开胃菜和主菜列表的索引。我不确定如何保留 app_ixentree_ix 的值,因为我无法在没有这些值的情况下调用 meal() 函数,按转义键将删除这些值并导致局部变量entree_ixapp_ix 没有值,但它们被作为 meal() 函数的参数调用错误

def screen(app,ent):
    mx,my = pygame.mouse.get_pos()
    if app == 1:
        running = True
        while running:
            window.fill(WHITE)
            window.blit(menu,(0,0))
            app_Box_one = pygame.Rect(WIDTH/3 - 100,HEIGHT/5,400,100)
            pygame.draw.rect(window,NUTMEG,app_Box_one)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if app_Box_one.collidepoint(mx,my):
                        running = False
                        app_ix = 0
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False

            pygame.display.update()
            main_clock.tick(60)
    if ent == 1:
        running = True
        while running:
            window.fill(WHITE)
            window.blit(menu,0))
            option_Box_one = pygame.Rect(WIDTH/3 - 100,option_Box_one)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if option_Box_one.collidepoint(mx,my):
                        running = False
                        entree_ix = 0
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False

            pygame.display.update()
            main_clock.tick(60)

def meal(app_index,entree_index):
    window.fill(WHITE)
    window.blit(menu,0))
    meal_font = pygame.font.SysFont('corbel',50,True)
    meal_message = app_list[app_index] + entree_list[entree_index]
    final_meal_message = meal_font.render(meal_message,True,BLACK)
    window.blit(final_meal_message,(WIDTH/2 - 50,HEIGHT/2 - 50))
    pygame.display.update



main()

解决方法

您应该在函数内部声明一个 global 变量。

def test():
    global gVar
    gVar = 10
    # Do stuff #

test()
print(gVar)

无论如何这是不好的编程习惯,通常如果你需要这样做,你就做错了其他事情。