Is there a way to bind a keyboard key to effectively push a button in PySimpleGUI?

83 Views Asked by At

In PySimpleGUI it appears only a mouse click will trigger an event. I've read the documentation and searched the web. The only keyboard key that is mentioned that will initiate an event is the return key. What I want to do is press the Hello button --in the code below-- by hitting the keyboard h key rather than using a mouse? Just wondering if there is a call or function that I'm missing?

import PySimpleGUI as sg
layout = [[sg.Button('Hello'),]]
window = sg.Window('Demo', layout)
while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    if event == 'Hello':
        print('Hello, World!')
window.close()
1

There are 1 best solutions below

2
Casandra Villagra On

PySimpleGUI does not support keyboard events out of the box. The window.read() function only returns events from the GUI elements like buttons, input fields, etc. It does not capture keyboard events.

However, you can use the bind method to bind a keyboard event to the window. Here's how you can modify your code to make it work:

import PySimpleGUI as sg

layout = [[sg.Button('Hello', key='-HELLO-', bind_return_key=True)]]

window = sg.Window('Demo', layout, return_keyboard_events=True)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    if event == '-HELLO-' or event == 'h':  # If 'h' key is pressed
        print('Hello, World!')

window.close()

In this code, return_keyboard_events=True is added to the sg.Window call. This makes the window return keyboard events. Now, when the 'h' key is pressed, the event 'h' is returned and the 'Hello, World!' message is printed.