Solution
import tkinter as tk
from tkinter import ttk
class TemperatureConverter:
def __init__(self, root):
self.root = root
self.root.title("Temperature Converter")
self.create_widgets()
def create_widgets(self):
# Entry for Temperature
temperature_label = ttk.Label(self.root, text="Enter Temperature:")
temperature_label.grid(row=0, column=0, padx=10, pady=10, sticky=tk.W)
self.temperature_entry = ttk.Entry(self.root)
self.temperature_entry.grid(row=0, column=1, padx=10, pady=10)
# Radio Buttons for Unit Selection
unit_label = ttk.Label(self.root, text="Select Unit:")
unit_label.grid(row=1, column=0, padx=10, pady=10, sticky=tk.W)
self.unit_var = tk.StringVar(value="Celsius")
celsius_radio = ttk.Radiobutton(self.root, text="Celsius", variable=self.unit_var, value="Celsius")
celsius_radio.grid(row=1, column=1, padx=10, pady=5, sticky=tk.W)
fahrenheit_radio = ttk.Radiobutton(self.root, text="Fahrenheit", variable=self.unit_var, value="Fahrenheit")
fahrenheit_radio.grid(row=1, column=2, padx=10, pady=5, sticky=tk.W)
# Convert Button
convert_button = ttk.Button(self.root, text="Convert", command=self.convert_temperature)
convert_button.grid(row=2, column=0, columnspan=3, pady=10)
# Result Label
self.result_label = ttk.Label(self.root, text="")
self.result_label.grid(row=3, column=0, columnspan=3, pady=10)
def convert_temperature(self):
try:
temperature = float(self.temperature_entry.get())
if self.unit_var.get() == "Celsius":
converted_temperature = (temperature * 9/5) + 32
result_text = f"{temperature:.2f} Celsius is {converted_temperature:.2f} Fahrenheit."
else:
converted_temperature = (temperature - 32) * 5/9
result_text = f"{temperature:.2f} Fahrenheit is {converted_temperature:.2f} Celsius."
self.result_label.config(text=result_text)
except ValueError:
self.result_label.config(text="Invalid input. Please enter a valid number.")
# Create the main window
root = tk.Tk()
# Create the TemperatureConverter instance
temperature_converter = TemperatureConverter(root)
# Start the Tkinter event loop
root.mainloop()