Search code examples
pythonpython-idle

How to display on the screen a different character from the pressed one with Python?


I'm trying to write a program that works like the website https://www.peteranswers.com/. That is, to display a character on the screen that is part of a previously written text, whichever is the character you type. My attempt is this:

f=open("text1.txt", "r")
g=open("text2.txt", "w")

while True:
        a = input()
        g.write(a)
        c = f.read(1)
        if not c or a == "$":
                break
        print (c)

f.close()
g.close()

It works, but I would like not to display the characters you type and not to have to press enter each time.

How could this be done? Does it exist a more straightforward way to accomplish this task?

I'm working on Python 3.7 and IDLE.


Solution

  • The site you link does not work for me. From the code, I presume that you want something that works like a password entry function. But you want the characters echoed to be taken from an existing text instead of being nothing or a stream of ' 's or '*'s.

    If so, I recommend that you modify the appropriate function, for Unix or Windows, in the getpass module. Note that both echo suppressing functions require that sys.stdout == sys.stdout (== system terminal and not None). Neither echo anything, you would have to add that. Neither work when you run in an IDE, such as IDLE, that rebind sys.stdout to print to a GUI.

    If you are on Windows, you should read https://docs.python.org/3/library/msvcrt.html#console-i-o. You would use putch to write bytes, or use both getwch and putwch to input and output unicode characters. On Unix, you will have to dig into the code yourself.