【问题标题】:Get Key Press in Python (pygame)在 Python 中获取按键(pygame)
【发布时间】:2019-05-08 17:09:39
【问题描述】:

我有一个 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,如果这会影响任何事情的话。

【问题讨论】:

    标签: python python-3.x pygame keyboard


    【解决方案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()   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 2015-10-31
      • 2016-03-19
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多