Python 3 wxPython Temperature Converter (Celsius + Kelvin + Fahrenheit) GUI Script Desktop App Full Project For Beginners

Python 3 wxPython Temperature Converter (Celsius + Kelvin + Fahrenheit) GUI Script Desktop App Full Project For Beginners

 

Welcome folks today in this blog post we will be building a temperature converter desktop app in wxpython in python. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to install the following library using the pip command as shown below

 

pip install wxpython

 

After installing this library you need to make an app.py file and copy paste the following code

 

app.py

 

import wx
import converters as conv


class TempConverterInterface(wx.Frame):
    def __init__(self, parent, style, title):
        super().__init__(parent, style=style, title=title, size=(310, 200))

        self.InitUI()
        self.Centre()
        self.Show()

    def InitUI(self):

        panel = wx.Panel(self)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)
        hbox = wx.BoxSizer(wx.VERTICAL)

        fgs = wx.FlexGridSizer(rows=4, cols=2, vgap=10, hgap=15)

        temp_value = wx.StaticText(panel, label="Temperature Value: ")
        temp_value.SetFont(font)
        from_temp = wx.StaticText(panel, label="From: ")
        from_temp.SetFont(font)
        to_temp = wx.StaticText(panel, label="To: ")
        to_temp.SetFont(font)
        calc_button = wx.Button(panel, label="Calculate")
        calc_button.Bind(wx.EVT_BUTTON, self.on_press_calculate)
        self.result = wx.StaticText(panel, label='', pos=(10, 10))
        font.SetPointSize(14)
        self.result.SetFont(font)

        self.tc1 = wx.TextCtrl(panel)
        self.tc2_combo = wx.ComboBox(
            panel, choices=["°C", "°F", "K"], style=wx.CB_READONLY)
        self.tc3_combo = wx.ComboBox(
            panel, choices=["°C", "°F", "K"], style=wx.CB_READONLY)

        fgs.AddMany([(temp_value), (self.tc1, 1, wx.EXPAND), (from_temp),
                     (self.tc2_combo, 1, wx.EXPAND), (to_temp, 1,
                                                      wx.EXPAND), (self.tc3_combo, 1, wx.EXPAND), (calc_button),
                     (self.result, 1, wx.RIGHT)])

        hbox.Add(fgs, proportion=1, flag=wx.ALL | wx.EXPAND, border=15)

        panel.SetSizer(hbox)

    def ShowValueErrorMessage(self):
        wx.MessageBox('You entered an invalid value.', 'Value Error',
                      style=wx.OK | wx.ICON_ERROR)

    def ShowTypeErrorMessage(self):
        wx.MessageBox('Origin and final temperature units must be different.', 'Unit Type Error',
                      style=wx.OK | wx.ICON_ERROR)

    def on_press_calculate(self, event):
        try:
            self.result.Label = conv.temperature_converter(value=float(self.tc1.GetValue()),
                                                           convert_from=self.tc2_combo.GetValue(),
                                                           convert_to=self.tc3_combo.GetValue())
        except ValueError:
            self.ShowValueErrorMessage()
        except TypeError:
            self.ShowTypeErrorMessage()


def main():

    app = wx.App()
    frame = TempConverterInterface(None, style=wx.MINIMIZE_BOX |
                                   wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX, title='Temperature Converter')
    frame.Show()
    app.MainLoop()


if __name__ == '__main__':
    main()

 

See also  Python 3 Subtitles Extractor From Youtube Video Script and Downloads it as .SRT File in Windows,Mac and Linux Using BeautifulSoup4 and Click Library Full Project For Beginners

 

Now make another module file inside the same root directory called converters.py file which will hold all the methods to convert the temperature from one format to another

 

converters.py

 

def temperature_converter(value, convert_from, convert_to):

    def celsius_converter(value, convert_to):
        """
        Converts from Celsius to Fahrenheit or Kelvin.
        """
        if convert_to == "°F":
            return f"{str((round(value * 9/5 + 32, 2)))} {convert_to}"
        elif convert_to == "K":
            return f"{str(round((value + 273.15), 2))} {convert_to}"

    def fahrenheit_converter(value, convert_to):
        """
        Converts from Fahrenheit to Celsius or Kelvin.
        """
        if convert_to == "°C":
            return f"{str(round((value - 32) * 5/9, 2))} {convert_to}"
        elif convert_to == "K":
            return f"{str(round((value - 32) * 5/9 + 273.15, 2))} {convert_to}"

    def kelvin_converter(value, convert_to):
        """
        Converts from Kelvin to Celsius or Fahrenheit.
        """
        if convert_to == "°C":
            return f"{str(round(value - 273.15, 2))} {convert_to}"
        elif convert_to == "°F":
            return f"{str(round((value - 273.15) * 9/5 + 32, 2))} {convert_to}"

    converters = {"°C": celsius_converter(value, convert_to),
                  "°F": fahrenheit_converter(value, convert_to),
                  "K": kelvin_converter(value, convert_to)
                  }
    return converters[convert_from]

 

See also  Python 3 Pillow Library Tkinter Drawing Paint Canvas Desktop GUI App Editor with Background Color and Pen Colors Full Project For Beginners

 

Now if you execute the python script app.py by typing the below command as shown below

 

python app.py

 

Leave a Reply