在Python中获取按键(pygame)

时间:2019-05-08 17:09:39

标签: python python-3.x pygame keyboard

我有一个python程序,该程序以pygame随机显示照片。我想使用全屏显示,但据我所知,没有任何简单的方法可以在不断开树莓派电源的情况下退出全屏显示窗口(导致严重问题)。我想创建一个代码块,该代码块不断轮询一次按键,并在检测到一个按键时使用quit()杀死程序。

我已经尝试实现thisthis,但是我不能让它们正常工作。

gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
events = pygame.event.get()
#get a random line from the txt file (imgs.txt)
def random_line():
    line_num = 0
    selected_line = ''
    with open('imgs.txt') as f: 
        while 1:
            line = f.readline()
            if not line: break
            line_num += 1
            if random.uniform(0, line_num) < 1:
                selected_line = line
    return selected_line.strip()
while True:       
    img_r = pygame.image.load(random_line())
    img_r = pygame.transform.scale(img_r, (1280, 1024))
    gameDisplay.blit(img_r, (0, 0)) #Replace (0, 0) with desired coordinates
    pygame.display.flip()
    time.sleep(1)

意外删除了我的有错误的旧代码,但这是错误

Traceback (most recent call last):
  File "/home/pi/Photo Frame/Photo Frame V1.0.py", line 29, in <module>
    GPE = get_pygame_events()
NameError: name 'get_pygame_events' is not defined

我希望在按下w键(这是我试图轮询的键)时退出窗口

如果您需要更多信息,只需询问

此外,如果有任何影响,我正在使用手动安装的GUI运行raspbian lite。

1 个答案:

答案 0 :(得分:1)

  

我希望在按下w键(这是我试图轮询的键)时退出窗口

您要做的就是添加一个事件循环。如果对 w 进行了操作,则开关将处于终止程序的状态:

run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        # set "run = False" if "w" is pressed
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:  
                run = False

    # [...]

pygame.quit()