-2

hi I am trying to merge a pygame program with pysimplegui.

i'm looking for a way of grabbing the downstroke of a keyboard key. at the moment i can only see an upstroke of the key no matter what im doing.

I have sucessfully created pysimplegui programs but this is the first time i'm trying to merge with pygame.

window is setup by

window = sg.Window('UNICHALL V2.0', 
                    Win_layout, 
                    border_depth =20,
                    resizable = True, 
                    keep_on_top = False, 
                    finalize=True,
                    return_keyboard_events=True,
                    use_default_focus=False) 

and in my pygame program i use

 for event in pygame.event.get(): 
    if event.type == pygame.KEYDOWN:
        stop = pygame.time.get_ticks()
        delta = stop - start
        key = event.key
        if key == 27:
            sys.exit(1) ...

i can't get these two work in harmony, they either internally loop forever or simply stop the program dead.

Any help appreciated.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Gadgettyke
  • 19
  • 6
  • 1
    Why use pygame ? just for the event key released or key presssed ? – Jason Yang Oct 13 '21 at 14:23
  • I used it fully for the other program initially, layout, inputs, images and sound the whole shebang. this time I've just used mixer all the rest in pysimplegui. However i can only get a key input when releasing the key when I need to edge detect the key down press for my program. will look at any suggestions you have for directly reading the keys, – Gadgettyke Oct 13 '21 at 17:02

1 Answers1

1

If you just need to detect when key pressed and released, try to bind the event '<KeyPress>' and '<KeyRelease>', not set option return_keyboard_events=True of sg.Window.

Example Code

import PySimpleGUI as sg


layout = [
    [sg.InputText('', key='-INPUT-')],
    [sg.Button('Add Binding'), sg.Button('Remove Binding')],
]

window = sg.Window('Test Program', layout, finalize=True)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    elif event in ('Press', 'Release'):
        e = window.user_bind_event
        action = 'pressed' if event == 'Press' else 'released'
        print(f'char:{repr(e.char)} | keycode:{e.keycode} | keysym:{e.keysym} | keysym_num:{e.keysym_num} {action}')
    elif event == 'Add Binding':
        window.bind("<KeyPress>", "Press")
        window.bind("<KeyRelease>", "Release")
    elif event == 'Remove Binding':
        window.TKroot.unbind("<KeyPress>")
        window.user_bind_dict.pop("<KeyPress>", None)
        window.TKroot.unbind("<KeyRelease>")
        window.user_bind_dict.pop("<KeyRelease>", None)

window.close()
Jason Yang
  • 11,284
  • 2
  • 9
  • 23