在执行其他操作的同时通过键盘事件退出pygame全屏显示

时间:2019-02-14 17:25:59

标签: python pygame

我想通过按 f 退出pygame显示的全屏模式。我了解我可以通过以下方式将全屏退出存档:

pygame.display.toggle_fullscreen()

并通过以下方式获取键盘事件:

    for event in pygame.event.get(): 
        if event.type == KEYDOWN:
            logging.warning("event")
            if event.key == K_f:
                logging.info("TOGGLE: toggle fullscreen")
                return 1 

我的问题是我需要保留初始化显示的功能。在事件发生之前,我不能呆在那里。但是我注意到,使键盘事件超出此功能不起作用(无显示->无键盘)。由于我不能有两个显示器,因此我可以为键盘事件记录一个“假”的显示器。如果没有相关事件,我也不想再次重建显示(否则,我可能会不时调用初始化函数并检查其中的事件)。

是否可能禁止使用键盘进行pygame?因此,我可以使用Keyboardinterrupt退出全屏显示吗?我想念什么吗?感谢您的任何帮助。我希望不要混淆。

1 个答案:

答案 0 :(得分:1)

pygame.display.toggle_fullscreen()的{​​{3}}状态:

  

此功能仅在UNIX X11视频驱动程序下有效。在大多数情况下,最好使用新的显示标志调用pygame.display.set_mode()。

因此,您似乎可能不得不重新创建顶级表面。

这是实现此目标的最小示例:

import pygame
pygame.init()

def init_screen(full=False):
    resolution = (1024, 768)
    if full:
        return pygame.display.set_mode(resolution, pygame.FULLSCREEN)
    else:
        return pygame.display.set_mode(resolution)

full_screen = False
screen = init_screen(full_screen)
finished = False
clock = pygame.time.Clock() #for limiting FPS
while not finished:
    for event in pygame.event.get():            
        if event.type == pygame.QUIT:
            finished = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                finished = True
            elif event.key == pygame.K_f:
                full_screen = not full_screen
                screen = init_screen(full_screen)
    if full_screen:
        screen.fill(pygame.color.Color("grey"))
    else:
        screen.fill(pygame.color.Color("aquamarine"))
    pygame.display.flip()
    clock.tick(60)
pygame.quit()

如果您需要进一步的说明,请告诉我们。