I made a script with pygame and keyboard to simulate a keyboard press when a controller button is pressed and it worked perferctly, but when trying to simulate an alt tab
, pygame
is doing something weird. Here is an example showing the code used to try an simulate alt+tab by pressing A and B on a XBox controller:
import pygame
from keyboard import press, release
pygame.init()
pygame.joystick.init()
Joy = pygame.joystick.Joystick(0)
Joy.init()
xbox_A_button_index = 0 # PS alternative: 2 for X
xbox_B_button_index = 1 # PS alternative: 1 for O
xbox_BACK_button_index = 6 # PS alternative: 8 for SHARE
running = True
while running:
for event in pygame.event.get():
if (
event.type == pygame.QUIT
or ( # Quit if the user presses BACK on the controller or the window is closed
event.type == pygame.JOYBUTTONDOWN
and event.button == xbox_BACK_button_index
)
):
running = False
if event.type == pygame.JOYBUTTONDOWN:
if event.button == xbox_A_button_index:
print("+ Alt")
press("alt")
if event.button == xbox_B_button_index:
print("+ Tab")
press("tab")
if event.type == pygame.JOYBUTTONUP:
if event.button == xbox_A_button_index:
print("- Alt")
release("alt")
if event.button == xbox_B_button_index:
print("- Tab")
release("tab")
When pressing A, then B, then releasing A and finally B, the above script gives me the following:
pygame 2.4.0 (SDL 2.26.4, Python 3.10.11)
Hello from the pygame community. https://www.pygame.org/contribute.html
+ Alt
+ Tab
- Alt
- Tab
+ Alt
- Alt
We should get something like:
pygame 2.4.0 (SDL 2.26.4, Python 3.10.11)
Hello from the pygame community. https://www.pygame.org/contribute.html
+ Alt
+ Tab
-Tab
-Alt
We should note that we ‘alt tab’ from the window, but I don't think it is the origin of the problem. I've tried pressing and releasing key with win32api
and win32com
to see if it has something to do with keyboard
module but nothing changed, I have no idea why this is happening and I did not find anything about this.
Any insight or suggestion would be helpful.
i think it is the problem of handling the events only once a frame. means, if you want to check for events that combine joystick and keyboard events, then you should store the event into a variable that can then be checked next frame, something like this: