Python Pygame:如何更改背景颜色
我试着问用户他想要什么背景色。如果用户写入红色,则颜色不会改变,仍然保持白色。下次更新显示时,它将重新绘制为红色。添加Python Pygame:如何更改背景颜色,python,python-3.x,pygame,Python,Python 3.x,Pygame,我试着问用户他想要什么背景色。如果用户写入红色,则颜色不会改变,仍然保持白色。下次更新显示时,它将重新绘制为红色。添加pygame.display.update(): 或者,在(有条件地)更改背景颜色后,可以将pygame.display.flip()移动到 另请参见创建变量以存储当前颜色: currentColor=(255255)#或“白色”,因为您创建了该值 background = input("What color would you like?: ") if background =
pygame.display.update()
:
或者,在(有条件地)更改背景颜色后,可以将pygame.display.flip()
移动到
另请参见创建变量以存储当前颜色:
currentColor=(255255)#或“白色”,因为您创建了该值
background = input("What color would you like?: ")
if background == "red":
screen.fill(red)
pygame.display.update()
在循环中:
background = input("What color would you like?: ")
if background == "red":
currentColor = red # The current color is now red
所以现在,当你需要重新着色屏幕时,只需将currentColor更改为你需要的任何颜色,屏幕就会自动改变该颜色。
例如:
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
顺便说一句,我认为最好将颜色存储为元组而不是列表,如
red=(255,0,0)
此外,除了循环中,您不需要在任何其他地方使用pygame.display.update(或flip)。此函数的作用是:它只需获取每个绘制项目的最新形状/值并将其推送到屏幕上,因此您只需要将其作为循环中的最后一个项目,这样它就可以显示所有内容。事实上,screen.fill(red)
更改曲面对象屏幕中像素的颜色。更改颜色后需要更新显示器。
但是,请注意,您应该只在应用程序循环结束时更新一次显示。每帧显示的多次更新会导致闪烁。另见
backcolor=白色
如果背景==“红色”:
背景色=红色
运行=真
运行时:
对于pygame.event.get()中的i:
如果i.type==pygame.QUIT:
运行=错误
#清晰的背景
屏幕填充(背景色)
#画场景
# [...]
#更新显示
pygame.display.flip()
说明:
您实际上是在一个对象上绘图。如果在与PyGame显示屏关联的曲面上绘制,则不会立即在显示屏上看到。当使用或更新显示时,更改将变为visibel
见:
这将更新整个显示的内容
虽然pygame.display.flip()
将更新整个屏幕的内容,pygame.display.update()
只允许更新屏幕的一部分,而不是整个区域pygame.display.update()
是pygame.display.flip()的优化版本,适用于软件显示,但不适用于硬件加速显示。请提供可运行的示例。您粘贴的内容在语法上不是有效的Python,并且在运行时会出错。由于缩进不正确(如果i.type==pygame.QUIT:
),代码末尾似乎有转录错误。pygame在缓冲区中绘制并且pygame.display.flip()
在监视器上发送缓冲区。请包括适当的缩进,以避免在第21行和第22行上运行时出现错误,因为它们需要再缩进一次才能正常运行。
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
if foo:
currentColor = (145, 254, 222)
elif bar:
currentColor = (215, 100, 91)