This article builds on the discussion from article 1 about creating a GUI program in Python.
In addition the labels, two other common elements for any UI are text boxes and buttons. Text boxes accept user entry, whose value can be retrieved and used by the program code. In this way, they are a graphical version of the input() statement. As with standard input, text entered into a text box is always a string. It must be converted to use it as a different data type.
A text box is declared as an Entry object type. It is placed on a frame in the same manner as a label.
If the simple window from the first article is re-imagined as a form that asks the user for their name and occupation, the right-side labels (Label2 and Label4) element might be replaced with text boxes. The revised window might look like the example below:
Here is the Frame1 code to replace 2 labels with text boxes:
Notice that the Entry function includes an attribute for "width". This sets the size of the text box in terms of the estimated numbers of characters that will be visible. It does not limit how many characters can be entered. The number of visible characters is also dependent on the font used for the text box. In this example, there are two text boxes with different lengths. This was done mainly to show how the width attribute works, although it is often helpful to guide the user with what the expected size of a text box entry should be.
You will also have noticed in the graphical example that the labels were much larger. You will see in the code example that an attribute for "font" was added to each label, including the font name and size.
Lastly, the code example uses different variable names for the UI elements. Because there can be so many elements on a single frame, it helps to use more descriptive variable names.
TKinter buttons are similar to other elements in the way they are created. Below is the code to add two buttons to the sample window above and a screen shot of what the window will look like.
Unfortunately, those buttons are very plain and not very attractive. There are several attributes that can be added to make elements look better, including padding and colors. The code below enhances the look of both buttons:
These are the attributes added to both buttons:
- padx: padding - number of pixels added to the right and left of the button text to expand the left and right button edges
- pady: padding - number of pixels added above and below the button text to expand the top and bottom button edges
- bg: background color: may be a standard name or an HTML hex number
- fg: foreground color: may be a standard name or an HTML hex number
Although the buttons look much better, nothing happens when they are clicked. The next article will demonstrate how to configure an event trigger to call a function when the button is clicked, allowing the program to react to the button click by take some action or actions.
Next article: Button Clicks & Event Handling.