0

I am using the latest version of PyCharm and Python. I'm trying to get my program to wait for specific keypresses like the arrow keys. I've been messing with the mscvrt (not worried about only windows) and using the getch() but it freezes my program everytime. I was able to get it to work printing to the console by using "emulate terminal in output console". But once I tried implementing it to a GUI with my code in tkinter it still freezes. Was wondering if it just doesn't work in GUI's and that's the issue (saw this mentioned on the internet) and if anyone had suggestions for what I could do.

For example:

This runs in the console and works. The arrow keys print as (b'\xe0' b'K') (left) and (b'\xe0' b'M') (right)

while True:
    if msvcrt.kbhit():
        key = str(msvcrt.getch())
        if key == "b'w'":
            print(key)
        elif key == 'w':
            print("suck it")

This freezes my program before I get the chance to press any keys. It seems to be only when I introduce GUI into the program. I also tried binding this as a function to space and it will freeze the GUI when I press space and crash after a bit. I also tried not using a while function and also without the kbhit part as well.

while True:
    if msvcrt.kbhit()
    user_input = str(msvcrt.getch())
    start = tk.Label(window, text=(user_input), font=("arial", '25'))
    start.place(relx=.5, rely=.7, anchor="center")

Appreciate any help/advice. I'm somewhat new to python and coding so not sure what the issue could be.

  • Oops, just btw the code under if was in the correct spot before I copy/pasted it here – lasketse12 Dec 15 '22 at 00:32
  • The problem is the infinite loop: [1](https://stackoverflow.com/questions/25731997/python-while-loop-causes-entire-program-to-crash-in-tkinter), [2](https://tkdocs.com/tutorial/eventloop.html). – 8349697 Dec 15 '22 at 07:03
  • Consider switching to Key/KeyPress [event handling](https://tkdocs.com/tutorial/concepts.html#events). – 8349697 Dec 15 '22 at 07:31
  • [Look for inspiration](https://stackoverflow.com/a/71594342/3439404)… – JosefZ Dec 15 '22 at 16:21
  • [Exactly as documented `msvcrt.getch()`](https://docs.python.org/3.10/library/msvcrt.html#msvcrt.getch): *If the pressed key was a special function key, this will return `'\000'` or `'\xe0'`; **the next call will return the keycode**.* – JosefZ Dec 15 '22 at 16:51
  • Thank you for the responses, I'll look into each one. – lasketse12 Dec 17 '22 at 23:31

0 Answers0