I am trying to make pygame quit when i press a “quit” button. however when setting my running bool to false my code keeps spitting out the text “test” and whenever i click the quit button it prints false, then goes right back to saying “test”. if printing running in both instances, it still prints false in the quit function but true in the while loop.
class Button:
def __init__(self, rect, bgcol, fgcol, text, function):
self.rect = rect
self.bgcol = bgcol
self.fgcol = fgcol
self.text = text
self.function = function
#textfill should be between 0 and 1
def DrawButton(button, textfill):
pygame.draw.rect(screen, button.bgcol, button.rect, border_radius = 2)
font_size = 10
while True:
font = pygame.font.SysFont('Arial',font_size)
w,h = font.size(button.text)
if((w > button.rect.width * textfill) | (h > button.rect.height * textfill)):
break
font_size += 1
text = font.render(button.text, True, button.fgcol)
x = button.rect.left + button.rect.width/2 - text.get_width()/2
y = button.rect.top + button.rect.height/2 - text.get_height()/2
screen.blit(text, (x,y))
buttons.append(button)
def CheckClick():
x,y = pygame.mouse.get_pos()
for button in buttons:
xcorrect = x > button.rect.x and x < button.rect.x + button.rect.width
ycorrect = y > button.rect.y and y < button.rect.y + button.rect.height
if(xcorrect and ycorrect):
button.function()
def Quit():
running = False
print(running)
buttons = []
screenW = 500
screenH = 500
screen = pygame.display.set_mode([screenW,screenH])
screen.fill([223,0,255])
rect = pygame.Rect(0,0,100,100)
rect.x = screenW/2 - rect.width/2
rect.y = screenH/2 - rect.height/2
bg = (0,0,0)
fg = (255,255,255)
QuitBtn = Button(rect, bg, fg, "Quit", Quit)
DrawButton(QuitBtn, 0.5)
running = True
while running:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
CheckClick()
print("test")
pygame.display.quit()
pygame.quit()
sys.exit()