在Python中获取按键(pygame)

在Python中获取按键(pygame),python,python-3.x,pygame,keyboard,Python,Python 3.x,Pygame,Keyboard,我有一个python程序,它以随机顺序显示照片,使用pygame来显示它们。我想使用全屏,但据我所知,如果不切断raspberry pi的电源(造成严重问题),就无法轻松退出全屏窗口。我想创建一个代码块,它不断地轮询按键,当它检测到有人使用quit()终止程序时 我已经尝试过实现,但我无法让它们正常工作 gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE) events = pygame.event.ge

我有一个python程序,它以随机顺序显示照片,使用pygame来显示它们。我想使用全屏,但据我所知,如果不切断raspberry pi的电源(造成严重问题),就无法轻松退出全屏窗口。我想创建一个代码块,它不断地轮询按键,当它检测到有人使用quit()终止程序时

我已经尝试过实现,但我无法让它们正常工作

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)
gameDisplay=pygame.display.set_模式((宽度、高度),pygame.resizeable)
events=pygame.event.get()
#从txt文件(imgs.txt)中随机获取一行
def random_line():
行数=0
选定的_行=“”
将open('imgs.txt')作为f:
而1:
line=f.readline()
如果不是行:断开
行数+=1
如果随机均匀(0,行数)<1:
选定的线=线
返回所选的_行。strip()
尽管如此:
img\u r=pygame.image.load(random\u line())
img_r=pygame.transform.scale(img_r,(12801024))
blit(img_r,(0,0))#用所需坐标替换(0,0)
pygame.display.flip()
时间。睡眠(1)
意外删除了有错误的旧代码,但以下是错误

回溯(最近一次呼叫最后一次):
文件“/home/pi/Photo Frame/Photo Frame V1.0.py”,第29行,在
GPE=获取游戏事件()
NameError:未定义名称“get\u pygame\u事件”
当我按下w键时,我希望窗口退出(这是我试图轮询的键)

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

此外,我正在使用手动安装的GUI运行raspbian lite,如果这会影响任何事情的话

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

您所要做的就是添加一个事件循环。如果选择w,开关将处于终止程序的状态:

run=True
运行时:
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
运行=错误
#如果按下“w”,则设置“run=False”
如果event.type==pygame.KEYDOWN:
如果event.key==pygame.K_w:
运行=错误
# [...]
pygame.quit()
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