I am trying to run the code below using python and pygame and I tried many things but i could find the solution for the program to detect the keyboard (arrows) events... And I am beginning to think that it is linked to the Catalina update of my Mac OS. Before the update, this code was working alright... I guess it has to do with the "Accessibility" between Python/Terminal and the rights I give to these 2 applications but I can't find the exact "right access" that solves the problem...
Anyone has an idea ? :)
# coding=utf-8
# imports the Pygame library
import pygame
def main():
# initializes Pygame
pygame.init()
# sets the window title
pygame.display.set_caption(u'Keyboard events')
# sets the window size
pygame.display.set_mode((400, 400))
# infinite loop
while True:
# gets a single event from the event queue
# event = pygame.event.wait()
pygame.event.pump()
# if the 'close' button of the window is pressed
if event.type == pygame.QUIT:
# stops the application
break
# captures the 'KEYDOWN' and 'KEYUP' events
if event.type in (pygame.KEYDOWN, pygame.KEYUP):
# gets the key name
key_name = pygame.key.name(event.key)
# converts to uppercase the key name
key_name = key_name.upper()
# if any key is pressed
if event.type == pygame.KEYDOWN:
# prints on the console the key pressed
print("{} key pressed".format(key_name))
# if any key is released
elif event.type == pygame.KEYUP:
# prints on the console the released key
print("{} key released".format(key_name))
# finalizes Pygame
pygame.quit()
if __name__ == '__main__':
main()
If you want to process keyboard events, use a for loop. For example:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
elif event.type == pygame.KEYDOWN:
print(f"{event.key} key pressed")
I'm not sure how your code worked before.
Related
I'm new to pygame. I have written the following code, but the generated window doesn't allow me to close it.
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
Looping and the game running are two different things. If you want to close the game after the loop ends, you should do so with pygame.quit(). Importing sys and adding sys.exit() as afterwards lets you exit the Python script altogether. Depending on which IDE you use, this may not happen automatically.
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((800,600))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit()
import pygame, sys
pygame.init()
wn = pygame.display.set_mode((500,500))
while True:
for event in pygame.event.get():
if event.type == pygame.quit():
pygame.QUIT()
sys.exit()
pygame.display.update()
wn.fill((255,255,255))
pygame.display.flip(bgcolor)
pygame.quit() is a function and uninitialize all PyGame modules. When you do
if event.type == pygame.quit():
the function is called and all PyGame modules are uninitialized.
The type attribute of pygame.event.Event() object indicates the type of event. You need to compare the event type to the enumeration constant that identifies the event. The quit event is identified by pygame.QUIT (see pygame.event module):
Hence, you have to compete with pygame.QUIT instead of pygame.quit():
if event.type == pygame.quit():
if event.type == pygame.QUIT:
Today is my first day of pygame and I cannot understand why this code doesn't work, the pygame windows is black doesn't respond and no image is displayed
import pygame
pygame.init()
screen_width=800
screen_height=800
screen=pygame.display.set_mode([screen_width,screen_height])
screen.fill((255,255,255))
Quit=input("Press'Y' is you want to quit")
if Quit == "Y":
pygame.display.quit()
Board = pygame.image.load("TicTacToeBoard.jpg")
screen.blit(Board,(0,0))
pygame.display.flip()
All PyGame programs have an Event Loop. This is a continual loop that accepts events from the window manager / operating environment. Events are things like mouse movements, button clicks and key presses. If you program does not accept events, eventually the launching program will consider it to have stopped responding and perhaps prompt the user to terminate it.
Your existing code grabs input from the console. This can be done in PyGame if you use a thread, and then post an event back to the main loop. But generally it's easier to just handle exiting as an event. In the code below I've handled exiting with the QUIT event, and pressing Q.
import pygame
pygame.init()
screen_width=800
screen_height=800
screen=pygame.display.set_mode([screen_width,screen_height])
Board = pygame.image.load("TicTacToeBoard.jpg")
clock = pygame.time.Clock()
# Main Event Loop
exiting = False
while not exiting:
# Handle events
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
exiting = True
elif ( event.type == pygame.MOUSEBUTTONUP ):
# On mouse-click
mouse_pos = pygame.mouse.get_pos()
print( "Mouse Click at "+str( mouse_pos ) )
elif ( event.type == pygame.KEYUP ):
if ( event.key == pygame.K_q ):
# Q is quit too
exiting = True
# Paint the screen
screen.fill((255,255,255))
screen.blit(Board,(0,0))
pygame.display.flip()
# Limit frame-rate to 60 FPS
clock.tick_busy_loop(60)
Additionally, this code also limits the frame-rate to 60 FPS.
PROBLEM:
if my mouse cursor is outside the window my game runs but if i have my cursor inside console gives me this error
Traceback (most recent call last):
File "c:/Users/jackw/Desktop/New folder/main.py", line 36, in <module>
if event.type == pg.QUIT():
TypeError: 'int' object is not callable
heres my code
import pygame as pg
from Config import *
from bin import *
# initialising pygame
pg.init()
class Game():
def background(self,background):
window.blit(background, (0,0))
# defining classes for use
g = Game()
# game loop
while isrunning:
# making sure the game is running on a constant clock
time.tick(fps)
# add background
g.background(gameback)
# setting up events
for event in pg.event.get():
# closing window event
if event.type == pg.QUIT():
isrunning = False
# input events
# show finished frame
pg.display.flip()
# Last code before closing the window
# closing the window
pg.quit()
most variables are defined in different files
config file
gamevars file
this program works fine on macOS I'm only getting this error on windows 10.
here's a video of the bug
QUIT is not a method or function, it is an enumerator constant, which specifies the type of the event (See pygame.event.Event()).
Remove the brackets to solve the issue:
if event.type == pg.QUIT():
if event.type == pg.QUIT:
pg.QUIT is an enumeration value. It's basically an integer. Your code added parentheses for some reason; this is invalid syntax. Use merely
if event.type == pg.QUIT:
What you coded is vaguely like
if event.type == 4():
I ran the code on my Macbook,it didn't work, while I ran the code on my Ubuntu it worked.
My macOS is 10.12.6
(ps:when I used mouse to control the image in pygame(just input the position of my mouse) ,if i didn't clicked the mouse , i can't dragged the image, but i didn't do anything in my program about click event)
This is my code
import pygame
pygame.init()
size = (800,600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('My Demo')
done = False
BLACK = (0,0,0)
WHITE = (255,255,255)
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
print('work')
screen.fill(WHITE)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Pygame sometimes mixes up the keys. I already have encountered this problem on Windows, it seems to be an issues on macOS too.
This approach might solve your problem: Pygame keyboard layouts mixed up.