在 Python (pygame) 中获取按键
Get Key Press in Python (pygame)
我有一个 python 程序可以随机显示照片,使用 pygame 来显示它们。我想使用全屏,但据我所知,没有简单的方法可以在不切断 raspberry pi 电源的情况下退出全屏 window(导致严重问题)。我想创建一个不断轮询按键的代码块,当它检测到一个按键时使用 quit()
终止程序
我已经尝试实施 this and this 但我无法让它们正常工作。
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
我预计 window 在我按下 w 键(这是我尝试轮询的键)时退出
如果您需要更多信息,请询问
此外,我是 运行 raspbian 精简版,具有手动安装的 GUI,如果这有任何影响的话。
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 程序可以随机显示照片,使用 pygame 来显示它们。我想使用全屏,但据我所知,没有简单的方法可以在不切断 raspberry pi 电源的情况下退出全屏 window(导致严重问题)。我想创建一个不断轮询按键的代码块,当它检测到一个按键时使用 quit()
终止程序我已经尝试实施 this and this 但我无法让它们正常工作。
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
我预计 window 在我按下 w 键(这是我尝试轮询的键)时退出
如果您需要更多信息,请询问
此外,我是 运行 raspbian 精简版,具有手动安装的 GUI,如果这有任何影响的话。
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()