Sunday, September 6, 2015

Learn Quickly Creating Professional Looking Desktop Application Using Python - Part 6 of 7

Binding Events to Methods

Quick links to other parts of this blog series:
Part-1 | Part-2 | Part-3 | Part-4 | Part-5 | Part-6 | Part-7 

All GUI applications are event-driven. An application reacts to different event types which are generated during its life. Events are generated mainly by the user of an application.

Working with events is straightforward in wxPython. There are three steps:
- Identify the event name
- Create an event handler. This is a function/method that is called when an event is generated
- Bind an event to an event handler

There are different types of events to different wxWidgets. For our expression Evaluator App, we will use only one event type called “OnButtonClick”. This event is generated when a user clicks on a button.

Let’s hook our buttons to event handler by following the steps above;-
~~ From our project (Eval_Project) in wxFormBuilder, select button1 (that’s Evaluate button) and the go to “Object Properties” panel on th right-hand side then select “Events” tab, you should see “OnButtonClick” event. See image-23
Type in the name of the event handler, I named mine “EvaluateFunc” (it can be any name meaningful). Do the same for button2 (that’s Close button), name it “CloseFunc”.

~~ Now regenerate the code file “gui.py” and open it in a text editor. Scrolling down (see image-24), you should notice that the file has been modified (wxPython minimum code will not be there) that means the file got replaced.

~~ As can see, the event handler names we defined for our buttons (“EvaluateFunc” and “CloseFunc”) are names for the functions or methods that are called when an “OnButtonClick” event is generated.
To create the “EvaluateFunc” function for the first button, override the event handler functions, by replacing the “event.Skip()” methods with the code that does whatever you want the buttons to do.

~~ We want the first button to evaluate an entered expression in the “EnterExpression” text box, so we will write a code for doing just that within the function.
As for the second button, we want it to close the frame so we will write a code that too inside the function.
Hence, the codes within our (“EvaluateFunc” and “CloseFunc”) function should look like the screen image-25 below;-

~~ Now, our Expression Evaluator App should work as expected if we entered a valid expression and clicked “Evaluate” button image-26. If an invalid expression is entered, error report is printed out.

Congrats!
That is it; our Expression Evaluator Application is now ready to be package and distributed!

I will talk about COMPILING, PACKAGING AND DISTRIBUTING OUR COMPLETED APP in the next class.





No comments:

Post a Comment