Search code examples
pythonuser-interfacemsvcrtpysimplegui

Using 'esc' to close PySimpleGUI window


I have a PySimpleGUI window that I want to maximise, eventually without a title bar. I want to use the 'esc' key to close the window.

Here's my (simplified) code:

import msvcrt
import PySimpleGUI as sg

layout = [[sg.Text(size=(40, 1), font=("Arial", (32)), justification='left', key='-TEXT-')]]
window = sg.Window(title="Window", layout=layout, grab_anywhere=True, finalize = True, no_titlebar=False)

window.maximize()

escape = False

while True:

    event, values = window.read()

    if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode():
        escape = True
    else:
        ecape = False

    if event == sg.WIN_CLOSED or event == 'Cancel' or escape == True:
        break

window.close()

The close button works fine - but pressing escape does nothing.

I've tried several of the answers here, but with no luck.

What's going wrong, and how can I fix it?


Solution

  • Solved.

    As @knosmos pointed out, getch is only for the command line. Adding return_keyboard_events=True and event == 'Escape:27' did the trick.