Search code examples
pythonpysimplegui

Key Binds not working in PySimpleGUI App. How to add shortcut keybinds in app?


I am trying to build a simple textbox window which closes after pressing Enter key. I tried several approaches, but none worked. Here's the code:

import PySimpleGUI as sg

init_layout = [
    [sg.Input('', size=(None, 5), background_color='white', border_width=0, key='-MULTILINE-')]
]

init_window = sg.Window('Enter File Name', init_layout, finalize=True)

while True:
    event, values = init_window.read()
    if event in (sg.WINDOW_CLOSED, '\r'):
        break

When I press enter key, nothing happens...

I tried using '\r' and also 'Enter', but that didn't work.


Solution

  • There're lot of ways to do it as following, then handle the event in your event loop.

    1. Binding window with the event '<Return>' after window finalized.
    # "Return" event
    window.bind("<Retrun>", "Return")
    
    1. Binding the Input element with the event '<Return>' after window finalized.
    # "-INPUT- Return" event
    window['-INPUT-'].bind("<Return>", " Return")
    
    1. Add one hidden Button with bind_return_key=True.
    # "Enter" event
    sg.Button('Enter', bind_return_key=True, visible=False)
    
    1. Add option return_keyboard_events=True to sg.Window.
    # '\r' event or 'Return:13' (It maybe different for different platform)
    window = sg.Window('Title', layout, return_keyboard_events=True)