Page 71 - Programming the Raspberry Pi Getting Started with Python
P. 71
Figure 7-4 The basic user interface for the Temp Converter application
The next step is to fill in the rest of the user interface. We need an “entry” into which a value for
degrees C can be entered and two more labels. We need one permanent label that just reads “deg F”
and a label to the right of it where the converted temperature will be displayed.
Tkinter has a special way of linking fields on the user interface with values. Therefore, when we
need to get or set the value entered or displayed on a label or entry, we create an instance of a special
variable object. This comes in various flavors, and the most common is StringVar. However, because
we are entering and displaying numbers, we will use DoubleVar. Double means a double-precision
floating-point number. This is just like a float, but more precise.
After we add in the rest of the user interface controls and the variables to interact with them, the
program will look like this:
The first DoubleVar (c_var) is assigned to the entry by specifying a textvariable property for it.
This means that the entry will display what is in that DoubleVar, and if the value in the DoubleVar is
changed, the field display will automatically update to show the new value. Also, when the user types
something in the entry field, the value in the DoubleVar will change. Note that a new label of “deg F”
has also been added.
The second DoubleVar is linked to another label that will eventually display the result of the
calculation. We have added another attribute to the grid command that lays out the button. Because
we specify columnspan=2, the button will stretch across both columns.
If you run the program, it will display the final user interface, but when you click the Convert
button, the message “Not Implemented” will be written to the Python console.
The last step is to replace the stubbed-out “convert” method with a real method that uses the
converters module from Chapter 5. To do this, we need to import the module. In order to reduce how
much we need to type, we will import everything, as follows: