Pygame: how to change background color

时间秒杀一切 提交于 2020-07-08 12:25:11

问题


import pygame, sys
pygame.init()
screen = pygame.display.set_mode([800,600])
white = [255, 255, 255]
red = [255, 0, 0]
screen.fill(white)
pygame.display.set_caption("My program")
pygame.display.flip()



background = input("What color would you like?: ")
if background == "red":
    screen.fill(red)

running = True
while running:
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
        running = False
        pygame.quit()

I'm trying to ask the user what background color he would like to have. If the user writes red, the color doesn't change and still stays white.


回答1:


It will redraw as red the next time you update the display. Add pygame.display.update():

background = input("What color would you like?: ")
if background == "red":
    screen.fill(red)
    pygame.display.update()

Or, you could move the pygame.display.flip() to after you (conditionally) change the background color.

See also Difference between pygame.display.update and pygame.display.flip




回答2:


Create a variable to store the current color :

currentColor = (255,255,255) # or 'white', since you created that value

background = input("What color would you like?: ")
if background == "red":
    currentColor = red # The current color is now red

in the loop:

while running:
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            running = False
            pygame.quit()

    screen.fill(currentColor) # Fill the screen with whatever the stored color is. 

    pygame.display.update() # Refresh the screen, needed whatever the color is, so don't remove this

So now, when you need to recolor the screen, just change currentColor to whatever you need, and the screen will automatically turn that color. Example :

if foo:
    currentColor = (145, 254, 222)
elif bar:
    currentColor = (215, 100, 91)

BTW, I think it is better to store color as a tuple instead of a list, like red = (255, 0, 0)

Also, you don't need pygame.display.update (or flip) anywhere else than in the loop. What this function does it just take the latest shape/value of every drawn item and pushes it to the screen, so you only need it as the last item in your loop, so it displays everything.



来源:https://stackoverflow.com/questions/41189928/pygame-how-to-change-background-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!