How do I randomize images in Python and how to blit image on top of image?

Viewed 142

I would like to address 2 questions:

1.) How do I randomize images in Python? I wanted to display a single image everytime I run my program. These are some snippets of my codes, but says some errors. The path was copy and pasted so I'm not so sure why there is an error.

import os
import random

path =r"D:\Files\Second Year Files\Advance Compprog\Final Project\Code Blocks\Images\Trivias"
files = os.listdir(path)
d = random.choice(files)
os.startfile(d)

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Trivia2.png'

I also tried to use this code but nothings shows up:

import pygame
import os
import random

# Initialize the pygame
pygame.init()

screenHeight = 550
screenWidth = 1000
screen = pygame.display.set_mode((screenWidth, screenHeight))

Trivias = [pygame.image.load(os.path.join("Images/Trivias", "Trivia1.png")),
            pygame.image.load(os.path.join("Images/Trivias", "Trivia2.png")),
            pygame.image.load(os.path.join("Images/Trivias", "Trivia3.png"))]

trivia = random.choice(Trivias)
screen.blit(trivia, [0,0])

2.) How to blit image on top of the other image? I tried to blit an image on top of an image but when I run the program, it will just either blink very fast or the last image that I use to blit will display. What if I wanted to blit the first image then, after some time interval, I wanted to overlap it with the other (both images have the same size and will be dsiplayed on the same position). How do I do that and put the time interval as well? I hope you could help me pls :(

  background_image = pygame.image.load(os.path.join("Images/Start", "Level1Lose.png"))
  screen.blit(background_image, [0, 0])
  pygame.display.update()
  hello_image = pygame.image.load(os.path.join("Images/Start", "hello.png"))
  screen.blit(hello_image, [0, 0])
  pygame.display.update()
1 Answers

Answer for question 1:

Check files variable. It is a list. It may be a list of only file names in that directory, which I think is the case. For proper functioning, it should be a list of paths to the file and not only the file name.

You can resolve this issue by passing path+d instead of only d

The same argument can be applied to the attempted case.

Related