Why does pygame freeze at pygame.event.get() when you move/drag the window? [duplicate] - python

This question already has answers here:
Pygame window not responding after a few seconds
(3 answers)
Pygame unresponsive display
(1 answer)
Closed 1 year ago.
Basically I have a loop (tick, set_caption, screen_fill, event.get(), send_frame_event, flip, repeat)
When I drag the window around on windows 7, the loop stops looping, I ended up stuck in pygame.event.get(), I have tried to define certain events only for get e.g. get([pygame.QUIT]) to no avail.
Simply calling pygame.event.clear() has the same freeze effect when dragging/moving the window.
Is there a workaround?
Not full code, but should be enough:
def start(self):
self.running = True
Clock = pygame.time.Clock()
while self.running:
self.p += 25
tickFPS = Clock.tick(self.fps)
pygame.display.set_caption("Press Esc to quit. FPS: %.2f" % (Clock.get_fps()))
self.screen.fill([self.p&0xFF,(255-self.p)&0xFF,255])
self.handleEvents()
self.raiseEvent("updateFrame")
pygame.display.flip()
def handleEvents(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.running = False
full code at: http://pastie.org/private/wm5vqq3f7xe0xlffy1fq

Try placing a call to pygame.event.pump() inside your mainloop (or handleEvents function)

No idea if this will help or not:
I realize the problem is with moving the window window, not with re-sizing the window.
Perhaps there is some similarity between moving and re-sizing?
I found this in the documentation on re-sizing:
Then the display mode is set, several events are placed on the pygame event queue. pygame.QUIT is sent when the user has requested the program to shutdown. The window will receive pygame.ACTIVEEVENT events as the display gains and loses input focus. If the display is set with the pygame.RESIZABLE flag, pygame.VIDEORESIZE events will be sent when the user adjusts the window dimensions. Hardware displays that draw direct to the screen will get pygame.VIDEOEXPOSE events when portions of the window must be redrawn.
and:
Note that when the user resizes the game window, pygame does not automatically update its internal screen surface. You must call set_mode() every time VIDEORESIZE is sent. This really should be more clear in the documentation.
Perhaps when moving the game window, something similar happens?

Related

Why an infinite "while True:" loop freeze the window and other that look similar not? [duplicate]

This question already has answers here:
Pygame window not responding after a few seconds
(3 answers)
Pygame unresponsive display
(1 answer)
How does the for event in pygame.event.get() in python work?
(1 answer)
Closed 3 months ago.
So, a while true loop that only passes, freezes the window. But a while true loop that checks the pool of events for a Quit event won't freeze. Why is that? checking the events take enough time to prevent the program from overloading? What is going on inside the hood?
Loop that freezes the Pygame window:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
while True:
pass
Loop that won't freeze the Pygame window:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
running = True
while running:
for e in pygame.event.get():
if e.type == pygame.QUIT:
running = False
So if both are running infinitely (The second one virtually, supposed that the QUIT event is never called), why the first one consumes so many resources that it overloads it an freezes the window, but the second one "behaves" and doesn't overload it, even if the exit condition of the loop is not called? Is there some waiting time in the pygame.event.get() function?
I tried looking for info on Google but I got lost in subprocesses, etc.

PyGame - Can't hide mouse

I've read everything I could find about the mouse in pygame and yet I miss something.
The device has (and will not) have a mouse attached so I need to remove the cursor from the game surface, ideally even before it draws the first screen.
But no matter what I try I always have a big oppalin cursor in the middle of the screen.
My current function is this :
# initialize the pygame module
pygame.init()
# create a surface on screen that has the size of 240 x 180
screen = pygame.display.set_mode((160,80))
# define a variable to control the main loop
running = True
pygame.display.flip()
# main loop
while running:
screen.fill((0, 0, 0))
# hide cursor
pygame.mouse.set_pos((160,80)) # my screen is actually 160 x 80 px so this should hide it by pushing it over the edge
pygame.mouse.set_visible(False) # this should hide the mouse plain and simple
# Here I do other unrelated (but working) stuff, like displaying images and text
# event handling, gets all event from the event queue
for event in pygame.event.get():
# only do something if the event is of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
running = False
pygame.display.flip()
And the mouse is still on screen, sometimes after a while it disappears.
I tried other method like making the cursor transparent, but that crash the app.
Note that I'm running Pygame on an Alpine Linux with direct output to the framebuffer on a Raspberry Pi. There's no mouse attached to the device but if I connect one I can move the cursor around.
Pygame is Version 2.1.2 (compiled and installed by pip)
Python is 3.10.0
Any help or pointer would be greatly appreciated.
(sorry if it's a dumb question; I'm a total noob with python/pygame)
Just write the set_visible(False) outside the main loop, you don't need to call this every frame:
pygame.init()
screen = pygame.display.set_mode((160,80))
pygame.mouse.set_visible(False) # Hide cursor here
running = True
pygame.display.flip()
# main loop
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# unrelated with your question but I also suggest that you clear your background inside the loop, at the contrary you likely will need this at each frame
screen.fill((0, 0, 0))
# ... your code, blitting images etc
pygame.display.flip()

Pygame screen crashes misterioslly, I don't idea Why [duplicate]

This question already has an answer here:
Pygame unresponsive display
(1 answer)
Closed 2 years ago.
I Was try to build a game and I was build the interfaces normally, but sundely pygame screen crashed and the pygame screen window becomes unresponsive always I run the a simple program.
import pygame
pygame.init()
pygame.display.init()
pygame.display.set_caption("Yathezz")
tela = pygame.display.set_mode((600,600))
preto = (0,0,0)
def set_telaPartida(tela,nome__jogador,pontos_totais, situacao):
tela.fill(preto)
#if(situacao == 1):
# set_telaLancaDados(tela,nome__jogador,pontos_totais)
# elif(situacao ==2):
# a = 1
# seta tela perguntando o relançamento
#elif(situacao == 3):
# b= 2
#set_telaRelancaDados
while True:
set_telaPartida(tela,"Lucas",100,1)
#set_telaInst2(tela)
pygame.display.update()
I have done some tests and I suspect that the problem are in this line
pygame.display.update()
But I don't have Idea what's happening. Could someone Help me???
You have to handle the events, by either pygame.event.pump() or pygame.event.get(), to keep the window responding. For instance:
run = Ture
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
set_telaPartida(tela,"Lucas",100,1)
#set_telaInst2(tela)
pygame.display.update()
See the documentation of pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. If you are not using other event functions in your game, you should call pygame.event.pump() to allow pygame to handle internal actions.
pygame.event.get() calls pygame.event.pump(). The pygame.QUIT occurs when the close button is pressed.

Getting position of user click in pygame

I have a pygame window embedded in a a frame in tkinter. In another frame I have a button which calls the following function when clicked:
def setStart():
global start
# set start position
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP:
start = event.pos
print("start",start)
break
I am intending for the program to print the position of the place where the user clicked on the pygame surface after the button is clicked. However on the first click of the button and the following click of the pygame surface there is no output. It is on the second click of the button before the corresponding second click on the pygame surface that python prints out an output like :
('start', (166, 115))
How can I get it to give me a result right after the click on the pygame surface? I had the same problem when I had two seperate tkinter and pygame windows so the embedding of pygame into tkinter is unlikely to be the cause of the problem.
EDIT: after further testing it appears that if the button is pressed and then the pygame surface is clicked on multiple times, upon a second click of the button the coordinates of all of these clicks are printed out as a batch.
In the most basic form here's how you do it in pygame:
import pygame
pygame.init()
screen = pygame.display.set_mode((100, 100))
clock = pygame.time.Clock()
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP: # or MOUSEBUTTONDOWN depending on what you want.
print(event.pos)
elif event.type == pygame.QUIT:
quit()
pygame.display.update()
More information on how to handle pygame events can be found in the docs.
And here's how you do it in tkinter:
try:
import tkinter as tk # Python 3
except ImportError:
import Tkinter as tk # Python 2
root = tk.Tk()
def print_pos(event):
print(event.x, event.y)
root.bind("<Button-1>", print_pos)
root.mainloop()
More information on tkinter events can be found in effbots documentation.
I would suggest not putting break in an event loop in pygame. Doing so makes all other events go un-handled, meaning that it's possible for the program to not respond to certain events.
Your "EDIT: [...]" is unfortunately wrong, given the code you've given us. I had no problem with the code; it printed the position of where I released the mouse button and always printed just one position. So there have to be a logical error somewhere else in your code.
First I have to say that I don't know anything about pygame. However, if you are already using Tkinter, I could help you maybe: I would define a new function (let's call it mouse_click). In the button-click-function I would bind the new function to the game's surface. In the new function I print out the current mouse position:
def button_click(self):
game_surface.bind("<Button-1>", self.mouse_click)
def mouse_click(self, event):
print "X:", event.x
print "Y:", event.y
I hope this is helpful. Please notice that you should modify this code to make it work in your program (using the correct widget names and so on).
By the way, "Button-1" is the event identifier of the left mouse button.

Not working quitting events in pygame.event

My program does only two things :
1) It's printing word 'hello' every time i hover mouse on one of two images (anyone,in any order)
2) It's closing , when i close window by pressing ESC , or by mouse
import pygame,sys ,os,random,math
from pygame.locals import *
pygame.init()
white=(255,255,255)
black=(0,0,0)
WINDOWWIDTH = 1680
WINDOWHEIGHT =1050
mousex, mousey=0,0
screen=pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))
ticket=pygame.image.load(os.path.join('imag','ticket.png'))
ticket2=pygame.image.load(os.path.join('imag','ticket2.png'))
def terminate():
pygame.quit()
sys.exit()
def checkForQuit():
for event in pygame.event.get(QUIT): # get all the QUIT events
terminate() # terminate if any QUIT events are present
for event in pygame.event.get(KEYUP): # get all the KEYUP events
if event.key == K_ESCAPE:
terminate() # terminate if the KEYUP event was for the ESc key
pygame.event.post(event)
tic1=ticket.get_rect(topleft=(50,770))
tic2=ticket2.get_rect(topleft=(220,770))
List_of_tickets=[tic1,tic2]
while 1:
screen.fill(white)
checkForQuit()
screen.blit(ticket,(50,770))
screen.blit(ticket2,(220,770))
for tic in List_of_tickets:
if tic.collidepoint(pygame.mouse.get_pos()):
print 'Hello !'
pygame.display.update()
The problem is that second part is not working !
So if i hover mouse on one ticket - everything fine . I got my 'Hello' word and i can close window if i need to .
But if i hover mouse on one ticket , and THEN on second ticket (so i got many more of my 'Hello' - and that's good) - i cannot quit program nor with ESC , nor with mouse.
It seems like quitting event ceased to be handled.
The questions are :
1) What i do not understand in handling of events in Pygame ?
2) What should i do to make my code quittin in any case ?
From the docs:
"If you are only taking specific events from the queue, be aware that the queue could eventually fill up with the events you are not interested."
Toss pygame.event.clear() in there and see what happens.
(If so, the reason it only fails if you go to both tickets is that all mouse movements add an event; moving to one ticket doesn't completely fill the queue, but moving to both does. Slightly wiggling the mouse would have the same effect.)

Categories