简体   繁体   中英

PyGame background color is not changing

I cannot find, what is wrong with background, even with debugger it is not doing nothing

#importing
from turtle import width
import pygame

#resolution
pygame.display.set_caption("Tanks")
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))

#background color (my problem)
def draw_window():
    WIN.fill((255, 0, 0))
    pygame.display.update()

#main functions
def main():
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
    pygame.quit()

#game start
if __name__ == "__main__":
    main()

You have to call draw_window in the application loop:

#importing
import pygame

#resolution
pygame.display.set_caption("Tanks")
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

#background color (my problem)
def draw_window():
    WIN.fill((255, 0, 0))
    pygame.display.update()

#main functions
def main():
    run = True
    while run:
        clock.tick(100)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        draw_window()
    
    pygame.quit()

#game start
if __name__ == "__main__":
    main()

The typical PyGame application loop has to:

When you write a function, it is just some instructions on memory, it doesn't run unless you call it. This is the case. You write a set of instructions, draw_window , but you never call it. What you need to do is before the game loop, call draw_window . So the code would be something like this.

#importing
from turtle import width
import pygame

#resolution
pygame.display.set_caption("Tanks")
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))

#background color (my problem)
def draw_window():
    WIN.fill((255, 0, 0))
    pygame.display.update()

#main functions
def main():
    run = True
    while run:
        draw_window()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
    pygame.quit()

#game start :)
if __name__ == "__main__":
    main()

This way the result will be a red window which is rgb(0, 0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM