如何在python上按键逐个打印列表元素



我想在控制台上打印一句话中的每个单词,但只有当用户按下空格键时,就像这样:乞讨时什么都不会发生;然后用户按下空格键,第一个单词出现并停留在那里;然后他/她再次按下空格键,第二个单词出现;等等:

<keypress> This <keypress> is <keypress> my <keypress> sentence.

我已经写了下面的代码,但我只能让所有的单词同时出现。

import pynput
from pynput.keyboard import Key, Listener
sentence = 'This is my sentence'
def on_press(key):
if key == Key.space:
i = 0
while True:
print(sentence.split()[i])
i = i + 1
if i == len(sentence.split()):
break
elif key == Key.delete:  # Manually stop the process!
return False
with Listener(on_press=on_press) as listener:
listener.join()

谢谢你的帮助。

import time
from pynput.keyboard import Key, Listener
SENTENCE = 'This is my sentence'
index = 0
stop = False

def on_press(key):
global index, stop
if key == Key.space:
if index < len(SENTENCE.split()):
print(SENTENCE.split()[index])
index += 1
else:
stop = True
elif key == Key.delete:  # Manually stop the process!
stop = True

with Listener(on_press=on_press, daemon=True) as listener:
while listener.is_alive() and not stop:
time.sleep(2)

最新更新