problem rising events with keyboard clicks in PySimpleGUI

Question:

I tried to find codes online about rising events in my PySimpleGUI program by simple keyboard clicks like ENTER or Ctrl+A for instance but I couldn’t just find any about it, I went to the documentation of PySimpleGUI and didn’t shut my tap without learning a thing.

Here is a simple code i wrote:

import PySimpleGUI as sg

layout = [[sg.I(key='In'), sg.B('Ok')],[sg.T(enable_events=True,key='T')]]

win=sg.Window("Keyboard Events", layout)

while True:
    event, value= win.read()
    #close event
    if event == sg.WIN_CLOSED:
        break
    #greeting evnt
    if event in ('Ok'): #( 'OK', 'KEYBOARD ENTER EVENT'):
        msg = "Hello "+value['In']  # message to show user
        win['T'].update(msg)        # show user message
        win['In'].update("")        # clear input field after submitting

win.close()

What should I say to PySimpleGUI for let it run #greeting event when I press the ENTER key? Can someone help me please? Thanks guys!

Asked By: A.M.M Elsayed

||

Answers:

Option required for element

  • sg.Input(do_not_clear=False, key='In') clear input field after event
  • sg.Button('Ok', bind_return_key=True) the return key will cause this button to be pressed
import PySimpleGUI as sg

layout = [[sg.I(do_not_clear=False, key='In'), sg.B('Ok', bind_return_key=True)],[sg.T(enable_events=True,key='T')]]

win=sg.Window("Keyboard Events", layout)

while True:
    event, value= win.read()
    #close event
    if event == sg.WIN_CLOSED:
        break
    #greeting evnt
    if event == 'Ok':
        msg = "Hello "+value['In']  # message to show user
        win['T'].update(msg)        # show user message

win.close()
Answered By: Jason Yang

Good question! And yes, its the documentation, not you. While this may not answer your question directly, here is some useful information.

You can choose to set return_keyboard_events=True as option when creating the window (sg.Window()). This will return every key hitting an input, as well as some scrolling events, meta keys, and so on.

window.read() returns a tuple (event, values). event can be:

  • None (sg.WIN_CLOSED)
  • A string of length one with the key from an input. For example ‘a’.
  • The key of a control. For example, ‘Ok’.
  • A tuple with more information. For example, clicking in a table gives a tuple of (keyname, "+CLICKED+", (row, column)
  • A special key, such as Return:6033979789 or Meta_L:922810622.

I use this as an alternative to bind_return_key when I might have multiple text entries on the screen:

    if isinstance(event, str) and event.startswith('Return'):
       event = 'return ' + self.window.find_element_with_focus().key

Also, I find printing to the console is necessary to debug events:

event, values = self.window.read()
print(f" event (type:{type(ui_event)}, {ui_event}, len:({len(ui_event)})"
      f" with values {ui_values}")
Answered By: Charles Merriam