Temperature converter that converts temp into Celsius, Fahrenhei

ghz 13hours ago ⋅ 3 views

Temperature converter that converts temp into Celsius, Fahrenheit and Kelvin using Tkinter

I want to create a program that converts temperature into Celsius, Fahrenheit and Kelvin by taking a valid input from the user which provides the converted temp respectively using if, elif, else. I just started learning tkinter so got no much idea about it, Kindly help me correct the source code.

import tkinter as tk
root = tk.Tk()
root.geometry("250x170") 
root.title('Temperature Converter')
frame=tk.Frame(root)
frame.pack()
l=tk.Label(root, text = "HELLO!!! Welcome to Temperature Converter") 
l.config(font =("Courier", 14)) 
l.pack()
t="Enter 1 To Convert Temperature Into Celsius.""\n"+"Enter 2 To Convert Temperature Into Fahrenheit.""\n"+"Enter 3 To Convert Temperature Into Kelvin."
l1=tk.Label(root, text = t,justify="left")
l1.config(font =("Courier", 14)) 
l1.pack(side="top",anchor="nw")  
def printtext():
    global e
    string = e.get() 
    print(string)  
e = tk.Entry(root,font =("Courier", 14))
e.pack(ipady=3,ipadx=3,anchor="center")
e.focus_set()

b = tk.Button(root,text='okay',font =("Courier", 13),command=printtext,anchor="center")
b.pack(side='top')
def Celsius():
    Fah=float(raw_input('Enter the temp in Fahrenheit')
    Celsius=(get(Fah)-32.0)*5.0//9.0)
    clabel=tk.Label(root,Celsius,text="Successfully Converted into Celsius")
    clabel.pack()
def Fahrenheit():
    Cel=float(raw_input('Enter the temp in Celsius')
    Fahrenheit=(get(Cel)*9.0//5.0+32)
    Flabel=tk.Label(root,Cel,text="Successfully Converted into Fahrenheit")
    Flabel.pack()
def Kelvin():
    Ces=float(raw_input('Enter the temp in Celsius')
    Kelvin=(get(Ces)+273)
    Klabel=tk.Label(root,Cel,text="Successfully Converted into Kelvin")
    Klabel.pack()  
def on_button():
    if e.get() == 1:
        Celsius()
    elif e.get() == 2:
        Fahrenheit()
    elif e.get() == 3:
        Kelvin()
    else: 
        tkinter.messagebox.showerror(title=None, message= "Invalid Choice")
root.mainloop()

Answer

Your code has several issues that need fixing. Here's a breakdown of the problems and how to correct them:

  1. Invalid Use of raw_input: In Python 3, raw_input() was replaced by input(). Additionally, the input you are getting from the user via tk.Entry should be used rather than input() in the console.

  2. Function Syntax Errors: There are several typos and syntax errors, such as missing parentheses and mismatched variable names.

  3. Global Variables and get() Method: get() should be used with the Entry widget to get user input. You don't need to use global e since e is already accessible.

  4. Output Formatting: You want to display the conversion result in the GUI, not in the console. So, you should use labels to show the results.

  5. Use of tkinter.messagebox.showerror: tkinter.messagebox needs to be imported for showing the error dialog.

  6. Function Calls and Variables: You should fix the way you are defining and calling the conversion functions.

Here's the corrected code:

import tkinter as tk
import tkinter.messagebox

# Function to convert to Celsius
def to_celsius(fahrenheit):
    return (fahrenheit - 32) * 5.0/9.0

# Function to convert to Fahrenheit
def to_fahrenheit(celsius):
    return (celsius * 9.0/5.0) + 32

# Function to convert to Kelvin
def to_kelvin(celsius):
    return celsius + 273.15

# Function to handle button click
def on_button():
    try:
        choice = int(e.get())  # Get the user's choice
        if choice == 1:
            fahrenheit = float(e2.get())  # Get the Fahrenheit value
            celsius = to_celsius(fahrenheit)
            result_label.config(text=f"Result: {celsius:.2f} °C")
        elif choice == 2:
            celsius = float(e2.get())  # Get the Celsius value
            fahrenheit = to_fahrenheit(celsius)
            result_label.config(text=f"Result: {fahrenheit:.2f} °F")
        elif choice == 3:
            celsius = float(e2.get())  # Get the Celsius value
            kelvin = to_kelvin(celsius)
            result_label.config(text=f"Result: {kelvin:.2f} K")
        else:
            tkinter.messagebox.showerror("Invalid Input", "Please enter a valid choice (1, 2, or 3).")
    except ValueError:
        tkinter.messagebox.showerror("Invalid Input", "Please enter valid numbers.")

# Set up the root window
root = tk.Tk()
root.geometry("300x250")
root.title('Temperature Converter')

# Create and pack the welcome label
l = tk.Label(root, text="Welcome to Temperature Converter", font=("Courier", 14))
l.pack(pady=10)

# Create the instructions label
instructions = """Enter 1 to Convert to Celsius.
Enter 2 to Convert to Fahrenheit.
Enter 3 to Convert to Kelvin."""
l1 = tk.Label(root, text=instructions, font=("Courier", 12), justify="left")
l1.pack(pady=5)

# Create an entry field for the user to input their choice (1, 2, or 3)
e = tk.Entry(root, font=("Courier", 14))
e.pack(pady=5)
e.focus_set()

# Create an entry field for the temperature value to be converted
e2 = tk.Entry(root, font=("Courier", 14))
e2.pack(pady=5)

# Create a label to display the result
result_label = tk.Label(root, text="Result: ", font=("Courier", 14))
result_label.pack(pady=10)

# Create a button to trigger the conversion
b = tk.Button(root, text="Convert", font=("Courier", 13), command=on_button)
b.pack()

# Run the Tkinter main loop
root.mainloop()

Explanation of Changes:

  1. Input Fields:

    • e is used for the user's choice (1, 2, or 3).
    • e2 is used for entering the temperature value (in Celsius, Fahrenheit, or Kelvin).
  2. Conversion Functions:

    • to_celsius(fahrenheit): Converts Fahrenheit to Celsius.
    • to_fahrenheit(celsius): Converts Celsius to Fahrenheit.
    • to_kelvin(celsius): Converts Celsius to Kelvin.
  3. Button Action:

    • The on_button function reads the input choice from e (which is the user's selection), converts the temperature based on the choice, and updates the result label with the converted temperature.
  4. Error Handling:

    • The try-except block is used to handle invalid inputs (e.g., non-numeric values).

How It Works:

  1. The user enters a number (1, 2, or 3) in the first entry box (e).
  2. The user enters the temperature value (in Celsius, Fahrenheit, or Kelvin) in the second entry box (e2).
  3. When the "Convert" button is pressed, the program checks the user's choice and performs the corresponding temperature conversion.
  4. The result is displayed in the result_label widget.

Example:

  • If the user enters 1 (for Celsius) and 32 (for Fahrenheit), it will convert 32°F to 0°C and display the result: Result: 0.00 °C.

This program should now work correctly, and it includes basic error handling for invalid inputs.