[Python] Why does my pygame class work at random intervals [closed]

Discussão em 'Python' iniciado por Stack, Junho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a class for buttons that draws and checks if they are clicked and changes its color. The drawing part works but the click check works half the time. I don't know the reson. Here's a simplified version:

    import pygame
    win = pygame.display.set_mode((800,600))

    run = True
    bcol = "gray"

    class button:

    def __init__(self,x,y,s,c):
    self.x = x
    self.y = y
    self.s = s
    self.c = c

    def click(self):
    mouse = pygame.mouse.get_pos()


    for ev in pygame.event.get():
    if ev.type == pygame.MOUSEBUTTONDOWN:
    if mouse[0]>=self.x and mouse[0] <= self.x + self.s and mouse[1]>=self.y and mouse[1]<=self.y+self.s:
    self.c = "white"

    else:
    self.c = "gray"

    return self.c

    def draw(self):
    pygame.draw.rect(win,(self.c),(self.x,self.y,self.s,self.s))

    while run:
    for ev in pygame.event.get():
    if ev.type == pygame.QUIT:
    run = False

    b = button(200,200,200,bcol)

    win.fill((70,70,70))

    bcol=b.click()
    b.draw()

    pygame.display.flip()

    Continue reading...

Compartilhe esta Página