Summary

Resources

Notes\ Code

image.png

Today’s final project is to built a miles to Km converter like the one seen above. Here’s some help for the layout.

image.png

Let’s do it.

My Solution:

from tkinter import *
FONT = ("Arial", 12)

window = Tk()
window.title("Miles to Km")
window.minsize(width=250, height=100)
window.config(padx=15, pady=15)

#Labels
is_equal_to_label = Label(text="is equal to", font= FONT)
is_equal_to_label.grid(column=0, row=1)

miles_label = Label(text="Miles", font= FONT)
miles_label.grid(column=2, row=0)

km_label = Label(text="Km", font= FONT)
km_label.grid(column=2, row=1)

km_output = Label(text="0", font= FONT)
km_output.grid(column=1, row=1)

#Entry
miles_input = Entry(width=10, justify="center")
miles_input.insert(END, string="0")
miles_input.grid(column=1, row=0)

def button_calc():
    new_miles = float(miles_input.get())
    miles_to_km = new_miles * 1.60934
    km_round = round(miles_to_km, None)
    km_output.config(text=km_round)

button = Button(text="Calculate", command=button_calc)
button.grid(column=2, row=2, padx=10, pady=10)

window.mainloop()

image.png

Project finished. Yay.

Transcript

It's time to put everything you've learned into practice and build our miles-to-kilometer converter. Let me show you the final result. This GUI program has a text entry field, several labels, and a button. You'll be able to type in a number of miles, hit calculate, and see the equivalent in kilometers. I've rounded it to the nearest whole number, but you can choose how many decimal places you prefer. The important part is making it functional and properly implementing all the components in the correct layout.

Looking at the layout, we have an entry widget, several label widgets, and a button widget arranged in a grid. Take a moment to plan the layout and design before diving into implementation. When you're ready, give it a try. You can either work in your main.py file (just comment out the existing code) or create a new file called mile_to_kilo_converter.py as I'm doing.

First, import everything from the tkinter module using "import *" to access all the classes. Next, create the window using the tk class and give it a title—"Miles to Kilometer Converter." Finally, display the window by starting the main loop. Running this file now shows a blank window with our title.

Now let's create and arrange our widgets. We need one entry widget, four label widgets at different positions, and a calculate button at the bottom. Let's create them one by one: