2016-12-16 303 views
1
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() 

我试图问用户他想要什么样的背景颜色。如果用户写红色,颜色不会改变,并仍然保持白色。Pygame:如何更改背景颜色

+0

请包含一个可运行的样本。你粘贴的内容不是语法上有效的Python,并且会在运行时出错。 – mwchase

+0

由于缩进不正确(在'if i.type == pygame.QUIT:'后面),代码的末尾似乎存在转录错误。 – e0k

+1

pygame在缓冲区中绘制并且'pygame.display.flip()'在监视器上发送缓冲区。 – furas

回答

3

下次更新显示时,它将重新绘制为红色。添加pygame.display.update()

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

或者,您也可以在pygame.display.flip()移动到后你(有条件)更改背景颜色。

又见Difference between pygame.display.update and pygame.display.flip

0

创建一个变量以当前颜色存储:

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 

在循环:

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 

所以现在,当您需要重新着色屏幕,只需将currentColor更改为任何你需要,屏幕会自动变成这种颜色。 例子:

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

顺便说一句,我认为这是更好地保存颜色作为一个元组,而不是一个列表,像 red = (255, 0, 0)

而且,你不需要pygame.display.update(或翻转)在循环中的任何地方。这个功能只需要将每个绘制物品的最新形状/值推送到屏幕上,因此您只需将其作为循环中的最后一项,即可显示所有内容。