Understanding Event-Driven Programming


GUI programs are traditionally event-driven, meaning they respond to actions regardless of the order in which they occur. Event-driven programming is a somewhat different way of thinking about coding. But don't worry, because if you've ever used a GUI before (like a Web browser), then you've already worked within an event-driven system.

To better understand the event-driven way, think about the Mad Lib final project from this chapter. If you were to write a similar program with your current Python skills, you'd probably ask the user a series of questions with the raw_input() function. You might ask for the name of a person, followed by a plural noun, followed by a verb, and so on. As a result, the user would have to provide each piece of information, in order. But, if you were to write the program in an event-driven way, say with a GUI, the user could enter the information in any order. Also, the timing of when the program actually generates the story would be up to the user as well.

When you write an event-driven program, you bind (associate) events (things that can happen involving the program's objects) with event handlers (code that runs when the events occur). As a concrete example, think about the Mad Lib chapter project again. When the user clicks the Click for story button (the event), the program invokes a method that displays the story (the event handler). In order for this to happen, I have to associate the button click with the story-telling method (I bind the two with each other).

By defining all of your objects, events, and event handlers, you establish how your program works. Then, you kick off the program by entering an event loop, where the program waits for the events that you've described to occur. When any of those events do occur, the program handles them, just as you've laid out.

Don't worry if this somewhat different way of thinking about programming isn't completely clear yet. After seeing a few working examples, you'll understand how to devise event-driven programs of your own.




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