Project Brief
Your task for this project is to create a desktop program that converts kilometers to miles. The program should have a desktop GUI. You can use any Python GUI library, but the code given in the solution section uses the Tkinter library.
Project Expected Output
Note that your GUI might look different, but its functionality should be similar to the following snapshot.
Environment Setup Instructions (in your local IDE)
👉 Skip to the next step if you prefer to code this project in an online browser-based IDE or from your mobile phone.
If you use Tkinter you don’t need to install anything.
Execute the main.py file once you have finished coding.
Environment Setup Instructions (in an online IDE as an alternative)
Prefer an online IDE? Use this cloud IDE link to start coding immediately in a pre-configured environment.
Resources
You can learn about creating GUIs with Tkinter in this post:
https://pythonhow.com/how/create-a-simple-tkinter-app/
I did mine, here is the code:
rom tkinter import Tk, Label, Entry, Button
# Conversion factor
conversion_rate = 0.621371
def convert():
"""
Retrieves user input, converts kilometers to miles, and displays the result.
:return:
"""
# Get kilometers value
try:
km_value = float(km_entry.get())
except ValueError:
# Handle invalid input
result_label.config(text="Invalid input. Please enter a number.")
return
# Calculate miles
miles_value = km_value * conversion_rate
# Display result with 2 decimal places
result_label.config(text=f"Distance in miles: {miles_value:.2f}")
# Create main window
window = Tk()
window.title("Km to Miles Converter")
# Label for kilometers entry
km_label = Label(window, text="Enter distance in kilometers:")
km_label.grid(row=0, column=0, pady=10)
# Entry field for kilometers
km_entry = Entry(window)
km_entry.grid(row=0, column=1, pady=10)
# Button to trigger conversion
convert_button = Button(window, text="Convert", command=convert)
convert_button.grid(row=1, columnspan=2, pady=10)
# Label to display conversion result
result_label = Label(window, text="")
result_label.grid(row=2, columnspan=2)
window.mainloop()
Very Interesting!