Buttons designed with PyGame won't change value of a variable

Question:

i hope you can help, because I’m running out of knowledge.
My Problem:
i want to change a variable to a new value:

def Schwierigkeit1():
    x = 1
    return x
    print(x)

therefore i call this function in my Button function:

def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac, (x, y, w, h))

        if click[0] == 1 and action != None:
            if (action == Schwierigkeit1):
                schwierigkeitComputer = Schwierigkeit1()
                print("Gegner auf Schwierigkeit: %d" % schwierigkeitComputer)

When i debug this, it shows me a good looking code and it seems to work.
BUT: This button call is set in a loop to build a starting screen for my game. Whenever the program comes back to this while-loop, the value of this variable gets resetted to the "Global" value.

schwierigkeitComputer = 0



def game_intro():
  while intro:
    pygame.display.set_caption('Spieleinstellungen')
    clock = pygame.time.Clock()
    intro = True
    pygame.init()
    gameDisplay.fill(white)

            for event in pygame.event.get():
                # print(event)
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

            button("1", 100, (ZEILEN + 230), 100, 50, white, LIGHTBLUE, Schwierigkeit1)

Did I mess anything up or do i not understand how a button with pygame works?

Thank you for your help.

Asked By: Lance

||

Answers:

If you want to change a variabel in global namespace within a function, you need to use the global statement:

def button(msg, x, y, w, h, ic, ac, action=None):
   
    global schwierigkeitComputer # <--- this is missing

    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac, (x, y, w, h))

        if click[0] == 1 and action != None:
            if (action == Schwierigkeit1):
                schwierigkeitComputer = Schwierigkeit1()
                print("Gegner auf Schwierigkeit: %d" % schwierigkeitComputer)
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.