Dispatching keypresses to embedded Pygame Dispatching keypresses to embedded Pygame tkinter tkinter

Dispatching keypresses to embedded Pygame


If there is no direct solution (of which I do not know), you could make a handler that passes the keypresses detected in tkinter to pygame.

The idea is to bind the keys to dispatch to a dispatch_event_to_pygame function, which will create a corresponding pygame.event.Event object, and to inject the latter into pygame's event loop, through the pygame.event.post function.

First, I define a dictionary that establishes the correspondence between the keys I want to dispatch from tkinter to pygame, and the corresponding symbols in pygame:

tkinter_to_pygame = {    'Down':     pygame.K_DOWN,    'Up':       pygame.K_UP,    'Left':     pygame.K_LEFT,    'Right':    pygame.K_RIGHT}

Then, I define a dispatch_event_to_pygame function, that takes a tkinter event, creates a corresponding pygame event, and posts it:

def dispatch_event_to_pygame(tkEvent):    if tkEvent.keysym in tkinter_to_pygame:        pgEvent = pygame.event.Event(pygame.KEYDOWN,                                     {'key': tkinter_to_pygame[tkEvent.keysym]})        pygame.event.post(pgEvent)

Finally, I bind on the root widget all the keys that I want to dispatch to pygame:

for key in tkinter_to_pygame:    root.bind("<{}>".format(key), dispatch_event_to_pygame)

References for the key names: