5. Temperature converter
This builds a simple temperature converter.
5.1. Get started
Click: Blank App.
Choose: Material Design
5.2. Settings
Click on the cog icon to show the settings tab.
Enter an App name. Temperature converter
Enter an App title. Temperature converter
Enter an App description. Converts temperatures
Get a thermometer icon to upload such as: https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Fahrenheit_Celsius_scales.svg/240px-Fahrenheit_Celsius_scales.svg.png
Click Change Image to upload an App logo.
Close the settings tab.
5.3. Build the first part of the interface
5.3.1. Card panel
5.3.2. Fahrenheit
5.3.3. Celcius
5.4. Code
celcius = (fahrenheit - 32) / 1.8
fahrenheit = self.fahrenheit.text
can be used to get the Fahrenheit temperature.if self.fahrenheit.text:
evaluates to True if a number has been entered or False if the textbox is empty.self.celcius.text = f'{celcius:.1f}'
can be used to place the calculated value formatted to 1 decimal place.except TypeError as error:
is used to clear the celcius value via: self.celcius.text = None
.def convert_click(self, **event_args):
try:
fahrenheit = self.fahrenheit.text
celcius = (fahrenheit - 32) / 1.8
self.celcius.text = f'{celcius:.1f}'
except TypeError as error:
self.celcius.text = None
5.5. Final Code
from ._anvil_designer import Form1Template
from anvil import *
import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables
class Form1(Form1Template):
def __init__(self, **properties):
# Set Form properties and Data Bindings.
self.init_components(**properties)
def convert_click(self, **event_args):
try:
fahrenheit = self.fahrenheit.text
celcius = (fahrenheit - 32) / 1.8
self.celcius.text = f'{celcius:.1f}'
except TypeError as er:
self.celcius.text = None
Tasks
Limit the fahrenheit input to a minimum of -459.67 (absolute zero).
Limit the fahrenheit input to a maximum of 7.2 trillion degrees (Large Hadron Collider).
Limit the fahrenheit input to a minimum of -459.67 (absolute zero).
def fahrenheit_change(self, **event_args):
if self.fahrenheit.text:
self.fahrenheit.text = max(-459.67, self.fahrenheit.text)
Limit the fahrenheit input to a maximum of 7.2 trillion degrees (Large Hadron Collider).
def fahrenheit_change(self, **event_args):
if self.fahrenheit.text:
self.fahrenheit.text = min(7200000000, self.fahrenheit.text)
Tasks
Add error checking with feedback. While the input filed has been restricted to numbers, typing a double negative sign is still possible. So make sure that en error message is shown if this is attempted.
Try making a distance converter such as miles to km or inches to cm.
Try making a mass converter such as lbs to kg.
Try making a volume converter such as gallons to litres.