So i am making a pygame
program and for that i have written a GUI.py
module. One of the classes is Button and one of the methods of that button is clicked, which basically checks if the button is being pressed. Initially i used pygame.mouse.get_pressed()
to check for mouse press, but the problem i had with that is that it registered multiple presses within a single frame, which is not what i want.
def clicked(self):
mouse_pos = pygame.mouse.get_pos()# Gets the position of the mouse
mouse_pressed = pygame.mouse.get_pressed()# Checks if the mouse is being pressed
# checking if the mouse is already inside the button
if self.mouseover():
# mouse_pressed[0] returns true if the left mouse button is being pressed
if mouse_pressed[0]:
return True
return False
So i need to use events to check for mouse press. However, i am importing GUI.py
to other modules, which are then imported to main.py
. Becasue of this, i cannot import main.py
to GUI.py
. But main.py
is where pygame.event.get()
is being called in the main loop. I could call the method in other modules and pass in events as an argument, but i want to do that every single time i make a button.
Sorry if what i tried to explain is unclear, but here is what the question boils down to. Is there a way to make pygame.event.get()
available to all the modules in my program independent of everything else?
The way i solved this in my pygame UI module was to store the previous frame click state, so if the mouse was clicked this frame and not last frame, its a click otherwise its being held down and nothing happens. (my module is a bit more complicated as it makes sure you clicked on it, then let go on it to count as a click)
if click and not previous_frame_click:
#clicked
if you are just using a function and not a class to do this, then maybe create a global variable
last_frame_click = False
def clicked(self):
global last_frame_click
mouse_pos = pygame.mouse.get_pos()# Gets the position of the mouse
mouse_pressed = pygame.mouse.get_pressed()# Checks if the mouse is being pressed
# checking if the mouse is already inside the button
if self.mouseover():
# mouse_pressed[0] returns true if the left mouse button is being pressed
if mouse_pressed[0] and not last_frame_click[0]:
last_frame_click = mouse_pressed
return True
last_frame_click = mouse_pressed
return False
EDIT: just noticed you said one of the classes, dont worry about above code, just use self.last_frame_click