python - 在Python中获取按键(pygame)

标签 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,如果这会影响任何内容。

最佳答案

I expected the window to quit when I pressed the w key (that was the key I was trying to poll)

您所要做的就是添加一个事件循环。如果 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()   

关于python - 在Python中获取按键(pygame),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045848/

相关文章:

python - Plotly:如何为每个变量创建具有不同样式和颜色的线图?

python - Pygame Mixer.music无法读取mp3流

python - mypy 提示 Incompatible return value type (got "Optional[str]"expected "str") when a function can only return str

python - 在 django 中重现 unicode 错误

python - 在 zip 对象列表上执行 len 会清除 zip

file - 如何在 python 中创建文件对象而不使用 open()

python - 错误 : OSError: libmediainfo. so.0:无法打开共享对象文件:没有这样的文件或目录

python - 如何在 Pygame 中进行两个单独的对象匹配旋转

python - 如何禁用 libpng 警告? ( python ,游戏)

python - 使用现有 SQLite 数据库中的两列使用 Python 创建第三列