Creating a GUI with Hard-Coding
Part 1 of creating a GUI to convert units.
We'll cover the following
We need the Tkinter
and Pint
libraries:
import tkinter as tk
import pint
Some people use the convention from tkinter import *
which imports everything from Tkinter without having to use the syntax tkinter.blah
. I prefer to import libraries the usual way (import tkinter as tk
) to avoid any potential namespace conflicts. This alternative syntax could create weird conflicts if Tkinter
had a function called blah()
, for example, and you unknowingly decided to create a different function called blah()
.
Using Tkinter
When making a GUI with Tkinter
, you need to decide if you are going to arrange elements by gridding them with grid()
or packing them with pack()
. Pack()
packs the elements sequentially as you create them, while grid()
allows you to grid according to row number and column number. You will use grid()
in all of your examples. If you mix grid()
and pack()
, your program will either error out, or it will run in an infinite loop but not display anything as it tries to figure out how to display elements that are gridded and packed (hint: it’s not possible, so Tkinter
will never figure it out).
All of the elements that you can create with Tkinter
are still Python objects; they can be manipulated, named, and renamed. “Widget” is a popular term that is used to label any object. Below is a table of the common Tkinter
widgets:
Tkinter Widget Name |
Description |
---|---|
Tk.Label |
A stage to display text |
Tk.Entry |
A text box where the user can write text |
Tk.Button |
A button to click |
Tk.RadioButton |
A selection radio button. Choose one option only |
Tk.CheckButton |
A selection checkmark button. Choose as many options as you want |
Tk.OptionMenu |
A dropdown menu. Choose one option only |
There are many more options, but these are usually the beginner’s most popular widgets.
The first step is to create the Tk
instance, set the width and height of the window, and name the window.
Get hands-on with 1400+ tech skills courses.