Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print list elements one by one by keypress on python

I want to print on the console each word in a sentence, but only when the spacebar is pressed by the user, like this: at the begging nothing happens; then the user press the spacebar and the first word appears and stays there; then he/she presses the spacebar again and the second word appears; and so on:

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

I’ve written the code bellow, but I could only make all the words appear simultaneously.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

Thank you for your help.

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading