How to react upon keypress while doing something?

for paragraph in intro.split("\n"):
  for character in paragraph:
    sleep(0.06)
    print(character, end="", flush=True)
  print()

The above code works great (assuming you have a variable called intro, that is). Is it possible to make it so that it will stop with the sleep delay and just print all the text if the user presses any key? Or do I have to just make a y/n question about the typewriter effect in the program?

2 Likes

have a seperate thread running with a deadlock saying whether or not there was a keypress. If there was, then terminate. You will need to do range to get the index you are current at and print all after that index

from threading import Thread
from getkey import getkey
stop = False
def __background():
     global stop
     getkey()
     stop = True

Thread(target = __background).start()
4 Likes

Sounds like a good idea but poetry and pip both fail to install getkey. It ran once and then now it crashes and can’t install getkey. I made a new Repl and had the same issue.

I think you should be able to do the same with fkeycapture here.

from fkeycapture import get
#Totally-not-plagarized
from threading import Thread
stop = False
def __background():
     global stop
     get()
     stop = True

Thread(target = __background).start()
1 Like

Fun fact: This package was made strictly because of getkey issues on Replit :upside_down_face:

2 Likes

That worked. One more question: where do I put the rest of the code?

I’d assume after the Thread call.

https://replit.com/@CoderElijah/NegligibleInfiniteCurrency
Help.

I will when I can.

def typewriter(text, delay=0.06):
  global stop
  for paragraph in text.split("\n"):
    if stop:
      print(paragraph)
      continue
    index = 0
    for character in paragraph:
      if stop:
        print(paragraph[index:])
        break
      sleep(delay)
      print(character, end="", flush=True)
      index+=1
    if stop: continue;
    print()
  stop=False

Should work I think.

That does indeed work. Thank you!

@CoderElijah Please change the method to what I just changed it to, I realized a glitch in my original code.

1 Like

Did you make this for me lol?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.