Displaying a Message


There may be times when you'll want to display some text on the screen for only a brief period of time. You may want to show a message saying "All records have been updated" or "Attack Wave Seven Complete!" The games class Message is perfect for creating temporary messages just like these.

Introducing the You Won Program

The You Won program is a modified version of the Big Score program. In fact, I instantiate just one Message object right before invoking the Screen object's main-loop() method to display the text "You won!" in big, red letters. The message is displayed for about five seconds and then the program ends. Figure 11.7 illustrates the program.

click to expand
Figure 11.7: Ah, the thrill of victory.

Creating a Message Object

Messages are created from the games class Message. A message is a special kind of Text object that destroys itself after a set period of time. A message can also specify a method or a function to be executed after the object destroys itself.

The constructor method for Message takes all of the values you saw with Text, but adds two more: lifetime and after_death. lifetime takes an integer value that represents how long the message should be displayed, measured in mainloop() cycles. after_death can be passed a method or function to be executed after the Message object destroys itself. The default value for after_death is None, so a value isn't required.

I create this Message object right before I invoke my_screen's mainloop() method with the following code:

 games.Message(screen = my_screen, x = SCREEN_WIDTH/2, y = SCREEN_HEIGHT/2,                text = "You won!", size = 100, color = color.red,                lifetime = 250, after_death = my_screen.quit) 

This creates the message "You Won!" in big, red letters at the center of the screen for about five seconds, after which the program ends.

This code instantiates a new Message object with a lifetime attribute set to 250. This means that the object will live for about five seconds, because mainloop() runs at 50 frames per second. After the five seconds, my_screen.quit() is called, since that's what I pass after_death. At that point, the Screen object and all of its associated objects are destroyed and the program ends.




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