首页 > 解决方案 > Pygame icon() 函数不改变全局变量

问题描述

我有一个功能,允许用户单击图标并设置一个布尔值,以便主循环知道要执行哪个操作。该代码旨在用作单击喷枪图标->设置airbrushMode为true->返回airbrushMode以便paintScreen()可以检测到它->执行airbrushModewhile循环中设置的操作。我在打印语句中添加了定位问题。变量确实发生了变化,但没有返回变量,并且喷枪功能不起作用。当我airbrushMode在内部设置为 truepaintScreen()但在函数中设置为 false 时,它​​确实有效,在函数外部都不起作用。

主要功能

def paintScreen():
    airbrushMode = False
    paint = True
    gameDisplay.fill(cyan)
    message_to_screen('Welcome to PyPaint', black, -300, 'large')
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    pygame.draw.rect(gameDisplay, white, (50, 120, displayWidth - 100, displayHeight - 240))
    while paint:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        button('X', 20, 20, 50, 50, red, lightRed, action = 'quit')
        icon(airbrushIcon, white, 50, displayHeight - 101, 51, 51, white, grey, 'airbrush')
        icon(pencilIcon, white, 140, displayHeight - 101, 51, 51, white, grey, 'pencil')
        icon(calligraphyIcon, white, 230, displayHeight - 101, 51, 51, white, grey, 'calligraphy')
        pygame.display.update()
        if cur[0] >= 50 <= displayWidth - 50 and cur[1] >= 120 <= displayHeight - 120:
            if airbrushMode == True:
                airbrush()

创建图标并检测动作,然后返回它的函数

def icon(icon, colour, x, y, width, height, inactiveColour, activeColour, action = None):
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x + width > cur[0] > x and y + height > cur[1] > y:#if the cursor is over the button
        pygame.draw.rect(gameDisplay, activeColour, (x, y, width, height))
        gameDisplay.blit(icon, (x, y))
        if click[0] == 1 and action != None: #if clicked
            print('click')
            if action == 'quit':
                pygame.quit()
                quit()
            elif action == 'airbrush':
                airbrushMode = True
                print('airbrush set')
                return airbrushMode
                print('airbrush active')

标签: pythonpython-3.xpygame

解决方案


您的问题是icon不尝试更改任何全局变量;它严格处理其输入参数和局部变量。如果您希望它更改自己范围之外的变量,则需要添加

global airbrushMode

在你的功能的顶部。

此外,如果您希望paintScreen识别全局变量,则必须具有该变量的全局存在(顶级用法),或者paintScreen还需要global声明。

有关完整的详细信息,请在 Python 中查找全局变量。


推荐阅读