Friday, January 24, 2014

How to load Image in Python ver 3.3 By Vicky Pramanik

Hi friends,

we are going to load an image in python 3.3 with pygame.
here are python code for loading image.


first we have to call pygame moudle. If you want to call an existing python file then you have to use 'import' keyword. We are using 'from' keyword and using '*' because we want import all locals from pygame.

# importing moudle
import pygame, sys
from pygame.locals import *

Python give commenting privilige. you can make comment using '#'. comments ignored by python interpreter.

Pygame.init() function is importent for running pygame successfully in your machine so it must be call before any other code.

# Pygame library  initialization
pygame.init()

Now we will creat window with 800 pixel width and 600 pixel height. we will creat a screen variable for holding display related data. the line [pygame.display.set_mode([width, height]) will creat your display window.

# Create an 800x600 sized screen
screen = pygame.display.set_mode([800, 600])

Now we will give a name to our newly created window. Again [pygame.display.set_caption('window name')] will give name to your window.

# This will  set up the name for the window
pygame.display.set_caption('Image Load Programme')

You can position your image through coordinate system. We are giving upper left position to our image. You can change image position as you like exmple :- background_position = [100, 200] 100 is representing 'X' and 200 is representing 'Y'

# Setting up positions of Image
background_position = [0,0]

Most awaited and soul of the programme is this line. To load image creat a variable and store this line in that variable.

# Loading Image .
background_image = pygame.image.load("math.png")

We have reached in the last section of our programme. Now we will free memory and quit from programme window. We will using 'while loop' and 'for loop' to handle this section. We are making while loop true because we want to run while loop every time. We will meet quit event using pygame inbuit event method and get function. We have called pygame and sys moudle so we have to exit from both modules. We have used 'pygame.display.update()' line for updating anything in the programme event for screen and window.

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()


Keep programming!

Coding Habit