Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hotkeys in PySimpleGUI

I'd like to write a GUI with PySimpleGUI that can be used entirely by keyboard. Based on the following sample code:

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

How can I add a hotkey which I can press using Alt+O to press the OK-Button? The O on the OK-Button should be underlined:

enter image description here

like image 277
Ohumeronen Avatar asked Oct 30 '25 21:10

Ohumeronen


1 Answers

A minimalist working example derived from: 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()
like image 164
Ohumeronen Avatar answered Nov 01 '25 10:11

Ohumeronen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!