使用 PyGame,我得到闪烁的东西。方框、圆圈、文字,都在闪烁。我可以通过增加循环之间的等待时间来减少这种情况,但我想也许我可以通过一次将所有内容绘制到屏幕上来消除它,而不是单独执行所有操作。这是发生在我身上的一个简单例子:
import pygame, time
pygame.init()
screen = pygame.display.set_mode((400, 300))
loop = "yes"
while loop=="yes":
screen.fill((0, 0, 0), (0, 0, 400, 300))
font = pygame.font.SysFont("calibri",40)
text = font.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
pygame.display.update()
font = pygame.font.SysFont("calibri",20)
text = font.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
pygame.display.update()
time.sleep(0.1)
“开始”按钮为我闪烁。它可能只是我的电脑速度较慢,但有没有办法减少或消除闪烁?在我正在处理的更复杂的事情中,它变得非常糟糕。谢谢!
请您参考如下方法:
我认为部分问题在于您多次调用“pygame.display.update()”。尝试在主循环期间只调用一次。
其他一些优化:
- 您可以将字体创建代码从主循环中取出来加快速度
- 做
loop = True而不是loop = "yes" - 要获得更一致的 fps,您可以使用 Pygame 的 clock类
所以...
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
loop = True
# No need to re-make these again each loop.
font1 = pygame.font.SysFont("calibri",40)
font2 = pygame.font.SysFont("calibri",20)
fps = 30
clock = pygame.time.Clock()
while loop:
screen.fill((0, 0, 0), (0, 0, 400, 300))
text = font1.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
text = font2.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
pygame.display.update() # Call this only once per loop
clock.tick(fps) # forces the program to run at 30 fps.
