【问题标题】:Using 'esc' to close PySimpleGUI window使用“esc”关闭 PySimpleGUI 窗口
【发布时间】:2021-04-29 18:32:08
【问题描述】:

我有一个想要最大化的 PySimpleGUI 窗口,最终没有标题栏。我想使用 'esc' 键关闭窗口。

这是我的(简化的)代码:

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()

关闭按钮可以正常工作 - 但按退出键没有任何作用。

我已经尝试了几个答案here,但都没有运气。

出了什么问题,我该如何解决?

【问题讨论】:

  • 很确定 getch 从命令行获取输入,而不是你的 pysimplegui 窗口

标签: python user-interface msvcrt pysimplegui


【解决方案1】:

解决了。

正如@knosmos 所指出的,getch 仅适用于命令行。添加return_keyboard_events=Trueevent == 'Escape:27' 就可以了。

【讨论】:

    【解决方案2】:

    将事件"<Escape>"绑定到窗口生成事件,

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2011-06-20
      相关资源
      最近更新 更多