1

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?

Kit McCarthy
  • 41
  • 1
  • 5

2 Answers2

2

Bind event "<Escape>" to window to generate an event,

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()
window.bind("<Escape>", "-ESCAPE-")

while True:
    event, values = window.read()
    if event in (sg.WINDOW_CLOSED, "-ESCAPE-"):
        break
    print(event, values)

window.close()
Jason Yang
  • 11,284
  • 2
  • 9
  • 23
0

Solved.

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

Kit McCarthy
  • 41
  • 1
  • 5