GUI Coding 3 - Button Clicks & Event Handling


This article builds on the discussion from article 2 that explained how to add a button to a Python window.


An event is something that happens when a user interacts with the UI, such as when the user clicks on a button. In this case, the trigger was a "click". For any element, the trigger might be a mouse-over, a blur (leaving a data entry field), a change in a data-entry field, etc.

In most UI's, these actions trigger an event. However, programs do not watch for or try to capture most events. In order to act on an event, the program must have an event handler.

Buttons always have an event handler; otherwise, the button has no purpose and no reason to be on the UI. An event handler calls a function when it is clicked.

Here are the code changes needed to the sample program to add two functions (btnGo_click() and btnClear_click()), and then event handler reference in each button - using the command attribute. Code for Button Event Handlers

Figure 1: Code for Button Event Handlers

The functions are created inside the Frame 1 class. They are named with a prefix using the button name, although that is not required. btnGo_clicked() creates a new label and places in on the window below the other elements. BtnClear_clicked() deletes the text in each text box.

Here is what the window looks like after each button is pressed:

Effect of Go Button Event

Figure 2: Effect of Go Button Event

Effect of Clear Button Event

Figure 3: Effect of Clear Button Event

Next article: Opening a New Window.