Pygame - Text won't appear on the window - python

I was displaying some text on the window but when i executed the code, it only showed a blank black window. I had no idea what was wrong, as no exceptions occurred. It just would not work.
Well i am an absolute beginner who have just passed some Python course for a couple of weeks, so i was just playing around the pygame module, instead of having big plans like game developing.
I also tried to search for similar problems but they are all so complicated that I can not understand quite well due to the long pieces of code.
I checked and no syntax is wrong, the font file is present, and the names of the objects are in the right place i.e. they are not using the wrong methods.
i don't know what else i can try...
import pygame as pg
pg.init()
win = pg.display.set_mode((720,540))
consolas = pg.font.SysFont("Consolas.ttf", 100)
text = consolas.render("hello", False , (255,255,255))
win.blit(text , (0,0))
i expected the string "hello" will be blited on the surface with the size of 100 and color to be completely white, but the whole thing did not show up at all.

You have to call pygame.display.flip or pygame.display.update to actually update the screen with the content of the win surface.
Also, you should have a main loop that handles events by calling pygame.event.get. This ensures your window stays open. Also, if you don't process events, your window becomes unresponsive and maybe doesn't even draw anything (depending on your OS/window manager)
So add this to your code:
run = True
while run:
for e in pg.event.get():
if e.type == pg.QUIT:
run = False
pg.display.update()

You need to use pg.display.update() or pg.display.flip() after you have drawn the text i.e. after win.blit line. The difference and use of the two can be found here : Difference between pygame.display.update and pygame.display.flip

As people have already commented that you have to call pygame.display.update() or pygame.display.flip()
Here's the full code:
import pygame as pg
pg.init()
win = pg.display.set_mode((720,540))
consolas = pg.font.SysFont("Consolas.ttf", 100)
running = True
while running:
text = consolas.render("hello", False , (255,255,255))
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
win.blit(text , (0,0))
pg.display.flip()
pg.quit()

Related

Pygame : The game stops temporarily when I am moving the window

I'm a new in PyGame and I was making a game. Until I discovered that when you were moving the window to another place of your desktop for example, the game temporarily stops. But ticks of the game still running when I used pygame.time.get_ticks().
So I made a completely new program with only the necessary code and it does the same thing.
Can someone explain me why it does it and if we can resolve this problem?
import pygame
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('The Test Program')
running = True
update_counter = 1
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
print(str(update_counter) + " updates")
update_counter += 1
pygame.quit()
quit()
# So try to move the window across your screen and you will see that, prints will stop and they will resume when you will release the click
So someone tell me that was normal, so I think it's only on Windows but there are no solutions. I put a script that show a pause symbol on screen when the cursor leave the window to make it normal.

Python Can't load background images in pygame

i try to load backgroud.png using pygame.image.load(),but i get nothing.here is my code,please help me ,thanks.
import pygame
pygame.init()
# screen
screen = pygame.display.set_mode((480, 700))
# 1.load_image
bg = pygame.image.load("./images/background.png")
# 2.blit
screen.blit(bg, (0, 0))
# 3.update
pygame.display.update()
while True:
pass
pygame.quit()
here is my sreen:it get nothing
With a game you're making all stuff that needs to be refreshed needs to be in the main game loop, your problem is, is you are drawing the image outside that game loop, meaning it gets drawn once then cleared and never drawn again.
To fix your code this is how you would write it:
import pygame
pygame.init()
# screen
screen = pygame.display.set_mode((480, 700))
# 1.load_image
bg = pygame.image.load("./images/background.png")
while True:
# 2.blit
screen.blit(bg, (0, 0))
# 3.update
pygame.display.update()
pygame.quit()
But notice how the bg=pygame.image... is outside the loop, this is because if it was inside the loop it would create a new instance of that image every time the loop happens.
The main game loop works by looping through all your functions and other stuff and then doing again and again, and again.
A game loop is how fps works, basically it is the measurement of how many times per second that game loop happens.
Make sure whenever you are doing anything in the loop it actually has a place there, for example loading an image doesn't, but updating where the player is on the screen does.
If you want to have a look at a good game loop that can be applied to most game engines this website will help you. But don't look at the most complex one when using pygame as it isn't built for that. Fix Your Timestep!
But your original problem of the image not loading isn't the case, it was loading but you were drawing your image in the wrong way, if you want a basic tutorial on pygame watch these videos: Game Development in Python 3 With PyGame - 1 - Intro
A better system to ease development
import pygame
bg = None
def load_resources():
bg = pygame.image.load("./images/background.png")
# all other resources
def render():
screen.blit(bg, (0,0))
def update():
# all logic updates for example movement of entities.
### start of game
load_resources()
while True:
update()
render()
pygame.display.update()
pygame.quit()
I think you should not write pass inside while loop because of it the output window will stop responding. Also you should write the screen blit and display.update inside while loop and you should write the correct image extension in the path. You can also write the full path of the file like ==> pygame.image.load(r"C:\Users\Desktop\back_ground.jpg")
import pygame
pygame.init()
# screen
screen = pygame.display.set_mode((480, 700))
# 1.load_image
bg = pygame.image.load("back_ground.jpg")
while True:
# 2.blit
screen.blit(bg, (0, 0))
# 3.update
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

Trying to display a png file in pygame using pygame.display.update, and it shows for less than a second then disappears.

The image is a playing card. We are using pygame 4.5 community edition and pycharm 2.6.9 because 2.7 does not support pygame (this is a school). Here is the code:
import pygame
pygame.init()
picture=pygame.image.load("cards/S01.png")
pygame.display.set_mode(picture.get_size())
main_surface = pygame.display.get_surface()
main_surface.blit(picture, (0,0))
pygame.display.update()
Why does the window disappear?
Try this:
import pygame
pygame.init()
picture=pygame.image.load("cards/S01.png")
pygame.display.set_mode(picture.get_size())
main_surface = pygame.display.get_surface()
main_surface.blit(picture, (0,0))
while True:
main_surface.blit(picture, (0,0))
pygame.display.update()
pygame.display.update() updates a frame. There are multiple frames per second depending on what what you draw onto the surface.
The problem is, after you update the screen with pygame.display.update(), you do nothing, and your program simply ends. pygame.display.update() does not block.
You need what is usually called a main loop. Here's a simple example with event handling:
import pygame
pygame.init()
picture = pygame.image.load("cards/S01.png")
# display.set_mode already returns the screen surface
screen = pygame.display.set_mode(picture.get_size())
# a simple flag to show if the application is running
# there are other ways to do this, of course
running = True
while running:
# it's important to get all events from the
# event queue; otherwise it may get stuck
for e in pygame.event.get():
# if there's a QUIT event (someone wants to close the window)
# then set the running flag to False so the while loop ends
if e.type == pygame.QUIT:
running = False
# draw stuff
screen.blit(picture, (0,0))
pygame.display.update()
This way, your application does not, only when someone closes the window.

Python pygame window keeps crashing

Whenever I run my code the Python Window that shows up does not respond.
Is there something wrong with my code or do I have to re-install pygame and python?
I get a black pygame window and then it turns white and says not responding?
Also I am new to this so please make this as simple as possible. I tried looking everywhere for the answer but could not get it in a way that I could understand.
Please help me out. Thanks :)
1 - Import library
import pygame
from pygame.locals import *
2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
3 - Load Images
player = pygame.images.load("resources/images/dude.png")
4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the screen elements
screen.blit(player, (100,100))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
Don't import pygame.locals. It is actually unnecessary, since you are already importing pygame.
Also, as #furas said, it should be:
player = pygame.image.load("resources/images/dude.png")
Not:
player = pygame.images.load("resources/images/dude.png")
This will clear up some of the problems in your code.
From my personal experience,if you run pygame code from IDLE it often does not respond at all.Try saving your project as a .py file and then run it with python.exe.It always works for me.
And as furas said use
player = pygame.image.load("resources/images/dude.png")
instead of
player = pygame.images.load("resources/images/dude.png")
Replace that for loop with this
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

Why Does PyGame Trail the Image? [duplicate]

This question already has answers here:
Pygame how to fix 'trailing pixels'?
(4 answers)
Closed 5 years ago.
I'm trying to develop a simple game in python using pygame and IDLE. I have, since yesterday, looked through a variety of sources in order to learn about the language (and programming in general), even so I have encountered some problems and misunderstandings of how it all works. So, if anyone could please advise me on how to proceed (or point me in the direction of some good learning material) then I would appreciate it greatly.
So far, I've got a small bit of code that forms the basis of my game idea, so I will post it here and list some of my problems.
import pygame
def main():
pygame.init()
logo = pygame.image.load("coolblack.jpg")
pygame.display.set_icon(logo)
pygame.display.set_caption("Battleship")
screenWidth = 800
screenHeight = 600
screen = pygame.display.set_mode((screenWidth, screenHeight))
bgd_image = pygame.image.load("grid.png")
#--------------------------------------------------------------------
#the image named 'image' should be above 'bgd_image' but below 'cv9'
#in fact, everything should be above bgd_image, especially 'cv9'
#--------------------------------------------------------------------
image = pygame.image.load("coolblack.jpg")
cv9 = pygame.image.load("ussessexcv9.gif").convert_alpha()
xposCv9 = 400
yposCv9 = 510
step_xCv9 = 1
step_yCv9 = 1
screen.blit(bgd_image, (0,0))
screen.blit(image, (400,300))
screen.blit(cv9, (xposCv9, yposCv9))
pygame.display.flip()
clock = pygame.time.Clock()
running = True
#---------------------------------------------
#I've got a pretty good idea (sort of) about
#what is happening in the section
#below this point, however it seems that
#the image 'cv9' creates a trail of itself
#every time it moves, so how could I make it
#so that it doesn't do so?
#---------------------------------------------
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
if xposCv9>screenWidth-64 or xposCv9<0:
step_xCv9 = -step_xCv9
if yposCv9>screenHeight-64 or yposCv9<0:
step_yCv9 = -step_yCv9
xposCv9 += step_xCv9
yposCv9 += step_yCv9
screen.blit(cv9, (xposCv9, yposCv9))
pygame.display.flip()
clock.tick(60)
if __name__=="__main__":
main()
The way that pygame works is that it has internally a representation of the screen which you are updating. So, it starts entirely black, then you do your first "blit". This will update the internal representation. Then when you call "pygame.display.flip" it shows that representation on the screen. However, this will not automatically "clear" the representation for you back to all black for your next frame. So, on the next frame, you blit again (slightly to the left, say), and the first blit remains, creating your "trail".
Therefore, for what you're doing, the best thing would be to in your loop, clear the internal representation of the screen before you start drawing the next frame. You can "clear" the screen by filling it with a single color, like so...
BLACK = (0,0,0)
....
screen.blit(cv9, (xposCv9, yposCv9))
pygame.display.flip()
clock.tick(60)
screen.fill(BLACK) # Add this to "clear" the screen.
Note that if you chose to go this route, this means you will need to redraw ALL of the elements every single frame (not just the ones that changed since the last frame).
BTW, in case you are wondering, there is a good reason for why the frame is not automatically cleared at the end. In some cases, it might be faster to only update the parts of the screen that update. This can cause performance speedups in some applications. However, it's probably best to start with clearing the screen as the example shows above.

Categories

Resources