Temperature Converter using Tkinter

Temperature Converter using Tkinter

Creating a simple temperature converter (Celsius to Fahrenheit and vice versa) using Tkinter in Python is a great beginner project for getting to know GUI development. Here's a simple example to guide you:

import tkinter as tk def fahrenheit_to_celsius(f): return (f - 32) * 5/9 def celsius_to_fahrenheit(c): return (c * 9/5) + 32 def convert(): if temp_var.get() == 'Celsius to Fahrenheit': result.set(celsius_to_fahrenheit(float(entry_value.get()))) else: result.set(fahrenheit_to_celsius(float(entry_value.get()))) root = tk.Tk() root.title("Temperature Converter") temp_var = tk.StringVar(value='Celsius to Fahrenheit') result = tk.StringVar() # Frame for the fields and buttons frame = tk.Frame(root, padx=10, pady=10) frame.pack(padx=10, pady=10) # Entry field entry_value = tk.Entry(frame, width=10) entry_value.grid(row=0, column=1, padx=5, pady=5) entry_value.insert(0, '0') # Default value # Dropdown to select conversion direction temp_selector = tk.OptionMenu(frame, temp_var, 'Celsius to Fahrenheit', 'Fahrenheit to Celsius') temp_selector.grid(row=0, column=0, padx=5, pady=5) # Convert button convert_button = tk.Button(frame, text="Convert", command=convert) convert_button.grid(row=1, columnspan=2, padx=5, pady=5) # Result label result_label = tk.Label(frame, textvariable=result) result_label.grid(row=2, columnspan=2, padx=5, pady=5) root.mainloop() 

This simple script creates a Tkinter window with:

  1. An Entry widget for the user to input the temperature value.
  2. A OptionMenu widget for the user to select the conversion direction (Celsius to Fahrenheit or vice versa).
  3. A Button that, when clicked, performs the conversion and displays the result.
  4. A Label that shows the conversion result.

The conversion formulas are defined in the functions fahrenheit_to_celsius and celsius_to_fahrenheit.

To use this converter, run the script, type a temperature into the entry field, choose the conversion direction, and click "Convert" to see the result.


More Tags

mousedown clob dynamics-crm influxdb maven-2 flutter-row tedious non-printable ejb-3.0 check-constraints

More Programming Guides

Other Guides

More Programming Examples