Please help fix bug: i can't close window import pygame import time red = (255, 0, 0) #…
- User
Please help fix bug: i can't close window
import pygame import time
red = (255, 0, 0) # 0 Red green = (0, 255, 0) # 1 Green blue = (0, 0, 255) # 2 Blue yellow = (255, 255, 0) # 3 Yellow magenta = (255, 0, 255) # 4 Magenta cyan = (0, 255, 255) # 5 Cyan white = (255, 255, 255) # 6 White black = (0, 0, 0) # 7 Black
def getColor(red, green, blue):
return (red, green, blue)def fillScreen(window, color):
window.fill(color)def drawLine(window, color, x0, y0, x1, y1, thickness):
pygame.draw.line(window, color, (x0, y0), (x1, y1), thickness)def setPixel(window, x, y, color):
window.set_at((x, y), color)def getWindow(title, width, height):
# Initialize Pygame pygame.init() window = pygame.display.set_mode((width, height)) pygame.display.set_caption(title) return windowdef app():
width = 1280 height = 720 window = getWindow("Sweden", width, height) # Main loop draw_delay = 500 # 500 milliseconds last_draw_time = pygame.time.get_ticks() ic = 0 while True: # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: break # Clear the screen window.fill((0, int(ic), 255-int(ic))) ic += 0.1 # Draw next pixel if the delay has passed current_time = pygame.time.get_ticks() if current_time - last_draw_time > draw_delay: window.set_at((100, 100), green) center_x, center_y = width // 2, height // 2 pygame.draw.line(window, red, (center_x, center_y), (center_x+100, center_y+100), 8) last_draw_time = current_time # Update the display pygame.display.flip() # Cap the frame rate pygame.time.delay(30) # Quit Pygame pygame.quit()if name == 'main':
app() - Assistant
The issue you're facing is that you're attempting to exit the loop using
breakwhen handling thepygame.QUITevent. However,breakonly exits theforloop and doesn't actually stop the mainwhileloop, which keeps the window open.To fix this issue, you should use a boolean variable to control the main loop, allowing you to properly exit it. Here's how you can modify your code to fix the bug:
def app(): width = 1280 height = 720 window = getWindow("Sweden", width, height) # Main loop draw_delay = 500 # 500 milliseconds last_draw_time = pygame.time.get_ticks() ic = 0 running = True while running: # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Clear the screen window.fill((0, int(ic), 255-int(ic))) ic += 0.1 # Draw next pixel if the delay has passed current_time = pygame.time.get_ticks() if current_time - last_draw_time > draw_delay: window.set_at((100, 100), green) center_x, center_y = width // 2, height // 2 pygame.draw.line(window, red, (center_x, center_y), (center_x+100, center_y+100), 8) last_draw_time = current_time # Update the display pygame.display.flip() # Cap the frame rate pygame.time.delay(30) # Quit Pygame pygame.quit()