Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help loading images using a for loop in PyGame [duplicate]

Tags:

python

pygame

I'm trying to load images in PyGame based on a value, like when the value is 6 it sets the image to be image number 6.

def bar():
    global ink
    global screen
    global barImg
    ink = 0
    for ink in range(0,100):
        barImg = pygame.image.load(f'inkbar\load{ink}.png')
        screen.blit(barImg,(100,100))
        pygame.display.update()

The value of ink gets changed in another function and I know that part works. Each image is called load0.png, load1.png and so on until 100, but the image never appears on the screen. I have tested putting the image on the screen by commenting out the for loop and just setting barImg to a specific image and it did put the image on the screen.

        px, py = pygame.mouse.get_pos()
        if pygame.mouse.get_pressed() == (1,0,0):
            pygame.draw.rect(screen, (255,255,255), (px,py,10,10))
            
            ink+=0.5
            math.ceil(ink)
            print(ink)

this is part of a function that allows the user to draw. This part detects mouse click and increases the value of ink. I tried calling bar() underneath the ink increase, but that decreased the rate of drawing.

I have removed the function bar()

            ink+=1
            math.ceil(ink)
            print(ink)
            for ink in range(1,100):
                barImg = pygame.image.load(f'inkbar\load{ink}.png')
                screen.blit(barImg,(100,100))

This is what I have used as a replacement, but now ink does not increase by one, it goes from 1 to 100 immediately, and causes large amounts of lag.

Maybe the images having "load" in the name is messing with something?

like image 531
Gummybearman06 Avatar asked Feb 18 '26 07:02

Gummybearman06


1 Answers

I have some code for running through frames of an animation which I know works

The code:

frame_index += animation_speed
if frame_index >= len(animation):
  self.frame_index = 0
image = pygame.image.load(f'Ink ({int(frame_index)}).png')
screen.blit(image, (0,0))
pygame.display.update()

Essentially you want to have two variables, a frame index and an animation speed. The index is the number of the first image you are loading. In this case Ink 0.png or whatever it's called. So your frame index will be 0. This will increment by your animation speed variable. The higher this is, the faster your animation will be. The lower, the slower. After it loops it will go back to 0 if thats what you want. If you don't want that then you can simply remove the if statement.

Also check that you aren't filling the screen AFTER doing this as whatever you're wanting to see will just be covered instantly. Let me know if this works.

like image 192
joelwright-dev Avatar answered Feb 19 '26 20:02

joelwright-dev