PySimpleGUI中的热键

3
我想用 PySimpleGUI 写一个可以完全通过键盘使用的 GUI。基于以下示例代码:
import PySimpleGUI as sg

layout = [[sg.Text("Hello from PySimpleGUI")], [sg.Button(button_text="OK")]]

window = sg.Window("Demo", layout)

while True:
    event, values = window.read()
    if event == "OK" or event == sg.WIN_CLOSED:
        break

window.close()

如何添加一个快捷键,我可以使用Alt+O按下“确定”按钮?确定按钮上的“O”应该带有下划线:

enter image description here


1
在 PySimpleGUI 的 GitHub 问题清单中展示了一种高级流程,用于查找像这样的答案。PySimpleGUI演示程序是起点。Demo_Hotkey.py具有您需要的绑定功能。下划线是一个扩展,由u/Ohumeronen在问题中发现。 - Mike from PSG
1
之前发布了一个名为psghotkey的PySimpleGUI应用程序,可以通过pip进行安装。这是我在我的系统上使用的。 - Mike from PSG
1个回答

3

以下是一个极简的工作示例,源自: https://github.com/PySimpleGUI/PySimpleGUI/issues/4122

import PySimpleGUI as sg

layout = [
    [sg.Button("ok", size=(10, 2), key='button1'),
     sg.Button("exit", size=(10, 2), key='button2')],
]
window = sg.Window('Hotkeys', layout, use_default_focus=False, finalize=True)
button1, button2 = window['button1'], window['button2']

window.bind("<Alt_L><o>", "ALT-o")
window.bind("<Alt_L><x>", "ALT-x")

button1.Widget.configure(underline=0, takefocus=0)
button2.Widget.configure(underline=1, takefocus=0)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event in ("button1", "ALT-o"):
        print('OK')
    elif event in ("button2", "ALT-x"):
        break

window.close()

1
你的解决方案,添加下划线的想法,启发了我现在将 & 字符添加到按钮文本中,就像在菜单中一样。 - Mike from PSG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接