TABLE 18.1 Window Widgets
Each widget has its own set of properties that define how it appears in the program window and how
to handle any data or actions that occur while the user interacts with the window.
Event-Driven Programming
Programming for a GUI environment is a bit different from command-line programming in the way
that Python handles the program code. In a command-line program, the order of the program code
controls what happens next. For example, the program prompts the user for input, processes the input,
and then displays the results on the command line, based on the input. The program user can only
respond to input requests from the program.
In contrast, a GUI program displays an entire set of interaction widgets all at once, all in the same
window. The program user gets to decide which widget gets processed next. Because code doesn’t
know which widget the user will activate at any given time, it has to use a feature called event-driven
programming to process code. In event-driven programming, Python calls different methods within
the program, based on what event (or action) happens in the GUI window. There isn’t a set flow to
the program code; it’s just a bunch of methods that individually run in response to an event.
For example, your user can enter data into a text widget, but nothing happens until the user presses a
button in the program window to submit the text. The button triggers an event, and your program code
must detect that event and then run the code method to read the text in the text field and process it.
The key to event-driven programming is linking widgets in the window to events and then linking the
events to the code modules in the program. An event handler is in charge of this process.
For the program to work, you must create separate modules that Python calls when it receives an
event from each widget. The event handlers do the bulk of the work in GUI programs. They retrieve
the data from the widgets, process the data, and then display the results in the window, using other
widgets. This may seem a bit cumbersome at first, but once you get used to coding with event handles,
you’ll see how easy it is to work in a GUI environment.