I recently made a small game and then turned it into an application using pyinstaller. When running, there are two ways to close it. It's fullscreen so clicking the red x button isn't included, but basically I have this
if keys[pygame.K_ESCAPE]:
pygame.quit()
and this
if exit_button.colliderect(cursor_rect) and click==1:
pygame.quit()
When the exit button is clicked, the game shuts down without a problem. The cursor shows the little loading symbol for a brief moment immediately after. However, when escape is pressed, the window closes but a message pops up saying, "Failed to execute script". I am on windows 10, the game was made with pygame on pycharm, and the exe was made with pyinstaller --onefile -w game.py.
Maybe it's a bug in the code, but it works perfectly fine in the IDE and I'm doing nothing different. I can also confirm it's not missing images or media. Thanks.
pygame.quit() doesn't quit your program, it uninitializes all pygame modules. It's meant to be used when you want the program to continue but without pygame. Your program will crash if you use certain pygame functions after calling pygame.quit().
If you want to terminate your program, simply let the program end naturally or call quit(). Many people like to call pygame.quit() before calling quit(), but this is actually not necessary.
Just want to add a little something.
As you'll see in most pygame projects (source), we use both pygame.quit() and sys.exit().
Assuming that your intention is to shut down both the pygame program and the Python script it's running from, you'll use something like the below code.
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
First pygame.quit() is called to stop all the pygame modules that activate when you run pygame.init(), followed by sys.exit() which stops the python script.
This is how I've been doing it for several projects that I've created and I've never had any errors while exiting the program, whether it be manually or through the code.
Related
I want to close the Pygame-Window after a specific event occurred and open it again after another event occurred without stopping the whole script. When I stop pygame with pygame.quit() and want to register a font or do whatever it gives me an error that says that pygame is not initialized so I coded it so it would call pygame.init() again after it closed the pygame window but as I read here pygame thinks it is still initialized and when I call pygame.init() again it won't really do anything. I don't get the error anymore but the code gets stuck at that point where I want to use pygame again, after I closed the pygame window with pygame.quit() and initialized it again, and then after 2 seconds, it just stops the script. How can I prevent pygame from doing this and reopen the pygame window without restarting the script?
Thank you.
What you are looking for is pygame.display.quit()
the following script display a pygame window for 1 second then close it
import pygame
import time
pygame.display.set_mode((1024, 668))
time.sleep(1)
pygame.display.quit()
pygame.quit() is the counterpart of pygame.init(). Not what you're trying to do.
I am writing a game using Pygame. When the game window opens, I currently only have the program call pygame.display.update after the game has changed something that shows on the screen. That works fine for limiting screen refreshes to only when necessary. I have discovered a side effect of moving the game window that causes the screen to get corrupted, which requires the program to force a refresh even if the program itself doesn't require one.
My question is if there is a pygame event (I didn't see one) or something else, that I can use to force the game to refresh the screen after a window move.
Okay, I happened across a code snippet that reports events to the console here:
http://www.poketcode.com/en/pygame/events/index.html
Running this was useful because I noticed that every time I moved the window partially off-screen, pygame triggered a VideoExpose event when the window area moved back on screen.
So, I added the following bit of code to my event loop and it worked great!:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.VIDEOEXPOSE:
game.update_panels(force=True)
game.update_panels(force=False)
I needed to make a simple thing and it seemed like a good starter project to learn python. I followed this GPIO music box tutorial (https://projects.raspberrypi.org/en/projects/gpio-music-box) and it runs fine in MU, Thonny Python IDE, but when I run on Geany it will open in a terminal, run end, produce no sound on button push. What I need is for this script to start automatically once raspbian is booted up and play back sounds at start. I've tried editing rc.local, bashrc, and crontab for automatic startup.
So this is running on a pi3 and the script looks like this basically:
import pygame from
gpiozero import Button
pygame.init()
drum = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/drum_tom_mid_hard.wav")
cymbal = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/drum_cymbal_hard.wav")
snare = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/drum_snare_hard.wav")
bell = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/drum_cowbell.wav")
btn_drum = Button(4)
btn_drum.when_pressed = drum.play
Is this not working because when the script is run in a terminal it doesn't import this python library? My only other experience programming is simple projects C# on Crestron units.
Thanks
A program run in terminal will terminate once it has executed all the code. If you want a program that passively sits and listens for user inputs, you need to add a loop to keep the program running. The basic structure looks like this (taken from https://realpython.com/pygame-a-primer/#setting-up-the-game-loop)
# Variable to keep the main loop running
running = True
# Main loop
while running:
# Look at every event in the queue
for event in pygame.event.get():
# Did the user hit a key?
if event.type == KEYDOWN:
# Was it the Escape key? If so, stop the loop.
if event.key == K_ESCAPE:
running = False
# Did the user click the window close button? If so, stop the loop.
elif event.type == QUIT:
running = False
If this structure is not familiar to you, the idea is that as long as the variable running = True, the program will keep going back to the while line every time it reaches the end. When you do want to end the program, such as allowing a user to press the escape key to quit, you add an event listener as shown that changes the running variable to false.
If I'm understanding your problem right, put all your initializations and imports at the beginning of the script, then all your event listeners in the loop. I highly recommend reading through the pygame documentation as well.
All you did was load in the sounds. In order to play the sound you need to type for example
drum.play()
in order for the drum sound to play.
I am making a game with Pygame that has some buttons, when touching a special button it's opening another .exe file. Im doing that with this way;
os.system("filename.exe")
But Pygame screen stays at background, I want to close that screen when the user click that button and open that .exe file. I tried this;
#codes
...
...
if action == "play":
os.system("filename.exe")
pygame.quit()
quit()
Theorically it should be work, opened .exe file after then quit from Pygame. But this isn't working, .exe file opened succesfuly but Pygame screen still stays at the background and if I touch it, giving error Pygame stop working.
How can I fix this? When that special .exe file opened, close the
Pygame screen?
os.system wait the program terminate; the next line pygame.quit will not executed until the termination of the process. Instead of os.system, you can use subprocess.Popen which does not wait the program termination (or any other functionality that does not wait the process termination):
import subprocess
....
if action == "play":
subprocess.Popen(["filename.exe"])
pygame.quit()
quit()
I have been writing a program in python using OpenCV. Up to this point, I had not set the mouse callback (cv2.setMouseCallback). To exit the program (which is in fullscreen), I would press the ESC key (Line 70).
I recently added a mouse callback (Line 11) which works as it should, however, now when I press the ESC key, the program does not terminate as it had previously. The while loop finishes, and cv2.destroyAllWindows() and sys.exit(0) are called. The window does close, and no python code after sys.exit(0) is executed, however no prompt is returned in Command Prompt (in which the python program was started).
My first thought was that there was a thread running that had not been stopped, however I have no threads in my code, and the thread that calls the onMouse function (Line 50) is the same as the main loop thread (i.e. it would not appear that opencv has a seperate thread for mouse callbacks).
My code can be found here: http://pastie.org/9246511
I am stumped, and any help is greatly appreciated.
Please note: You will need a webcam plugged in to test the code
Your code seems to exit correctly running it as a script from a prompt and running in Pycharm when using sys.exit().
If you are running it in Ipython you need to use exit() to return to the command prompt:
Just use exit() after cv2.destroyAllWindows() and it will terminate.
In [1]: type(exit)
Out[1]: IPython.core.autocall.ExitAutocall
Just incase you never got the answer...I just had the same issue. Turns out it was because in my my config file (Run/Debug Configurations) I had checked the "Show command line afterwards" box. Once I unchecked that the window was killed correctly.