Setting a Background Image


A blank screen is all well and good, if your goal is to create the world's most boring program. Fortunately, the Screen class has a method to set a background image.

Introducing the Background Image Program

The Background Image program is just a modification of the New Graphics Window program. I add only two lines of code to create a graphics window with a background image. By taking advantage of Screen's background-setting method the program produces the window shown in Figure 11.4.

click to expand
Figure 11.4: By using the set_background() method, a background image can be applied to a Screen object.

To create the Background Image program, I add two lines to the New Graphics Window program, just before invoking mainloop().

Loading an Image

Before you can do anything with an image, like set it as the background of a graphics screen, you have to load the image into memory to create an image object. I load an image by adding the following line after right after I create the graphics screen:

 wall_image = games.load_image("wall.jpg", transparent = False) 

This calls the games load_image() function, loads the image stored in the file wall.jpg into memory, and assigns the resulting image object to wall_image.

TRAP

Make sure that any file you want your Python program to access is associated with the correct path information, as you learned in Chapter 7, in the section "Opening and Closing a Text File." The simplest file management solution, and the one I use here, is to store image files in the same folder with the program that loads them. If you follow this method, you won't need to worry about path information at all.

The load_image() function takes two arguments: a string for the file name of the image and True or False for transparent. I'll go over exactly what transparent means a bit later in this chapter. For now, just remember this rule: Always load a background image with transparent = False.

You'll notice that I load a JPEG image for the background in this program. However, you're not restricted to JPEGs when using the load_image() function. It works just as well with many other image file types, including: BMP, GIF, PNG, PCX, and TGA.

Setting the Background

In order to set an image object as the background of a Screen object, you need to invoke the Screen object's set_background() method, so I add the following line right after I load the image:

 my_screen.set_background(wall_image) 

This sets the background of my_screen to the image object referenced by wall_image. You can use this method with any Screen object and image object.

When the program encounters mainloop(), it keeps the graphics window open, with its new background image, for all to see.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net