Python Pygame:如何更改背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41189928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pygame: how to change background color
提问by user7307944
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.
我试图询问用户他想要什么背景颜色。如果用户写红色,颜色不会改变并且仍然保持白色。
回答by e0k
It will redraw as red the next time you update the display. Add pygame.display.update()
:
下次更新显示时,它将重绘为红色。添加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.
或者,您可以pygame.display.flip()
在(有条件地)更改背景颜色后移动to。
See also Difference between pygame.display.update and pygame.display.flip
回答by underscoreC
Create a variable to store the current color :
创建一个变量来存储当前颜色:
currentColor = (255,255,255) # or 'white', since you created that value
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 :
所以现在,当您需要重新着色屏幕时,只需将 currentColor 更改为您需要的任何颜色,屏幕就会自动变为该颜色。例子 :
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)
顺便说一句,我认为最好将颜色存储为元组而不是列表,例如
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.
此外,除了循环之外,您不需要 pygame.display.update (或翻转)。这个函数所做的只是获取每个绘制项目的最新形状/值并将其推送到屏幕上,因此您只需要它作为循环中的最后一个项目,因此它会显示所有内容。