Create GUIs with Python using Tkinter

Create GUIs with Python using Tkinter

·

5 min read

What is TKinter?

Tkinter is a built-in Python GUI framework that is lightweight and easy to start with. It is also cross-platform, which means the same Python code will work on Windows, macOS, and Linux. However, styling of the application is somewhat limited and it definitely not the most beautiful GUI frameworks to work with. Regardless, it is a great choice for building simple projects where functionality trumps over its visual.

Creating GUIs using TKinter

Import TKinter

To user the TKinter library, it is as simple as one line of code:

from tkinter import *

Create Our Main Class

We define a new class called 'Application' that inherits the Tk class from the tkinter library. Next, we initialize a constructor for our class with our chosen layout manager. Here, we are using the grid layout.

class Application(Tk):
    def __init__(self):
        # Call the constructor of our parent class
        super().__init__()
        # Layout manager
        self.grid()

Adding Widgets

And just like that, we are ready to add some widgets onto our app! To add a new widget to our application, we can call the grid() method. It takes in several optional arguments:

  • column: the column to put widget in; default 0 (leftmost column).
  • columnspan: how many columns widget occupies; default 1.
  • ipadx, ipady: how many pixels to pad widget, horizontally and vertically, inside widget's borders.
  • padx, pady: How many pixels to pad widget, horizontally and vertically, outside v's borders.
  • row: the row to put widget in; default the first row that is still empty.
  • rowspan: how many rowswidget occupies; default 1.
  • sticky: what to do if the cell is larger than widget. By default, with sticky='', widget is centered in its cell. Sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks.

Now that we know how to add widgets to our grid layout, let's create them!

Frame

  • Displays just as a simple rectangle
  • Primarily used as a container for other widgets, which are under the control of a layout manager such as grid

To create a new Frame widget, we specify the height and width. Then we can add it to our layout.

frame = Frame(height=20, width=640)
frame.grid(row=0, column=0)

Besides height and width, some other common extra arguments we can pass to style this widget

  • padding
  • relief ('FLAT', 'RAISED', 'SUNKEN', 'GROOVE', or 'RIDGE')
  • borderwidth

Label

  • Displays text or images
  • Used for such things as identifying controls or other parts of the user interface, providing textual feedback or results, etc.

Example 1: Creates a Label widget with a white 'Hello World!' text, with blue background.

label = Label(text='Hello World!', fg='white', bg='blue')

Example 2: Creates a Label widget that displays an image

my_image = PhotoImage(file='myimage.png')
label = Label(image=my_image)
label.image = my_image

Note: doesn't support .jpg files

Other common optional arguments

  • justify: Alignment of text: left, center or right
  • textvariable: As an alternative to text, get the string from a variable, updating when the variable changes)
  • wraplength: For multi-line labels; let Tk calculate the line breaks rather than explicitly embedding newlines in the text string)

Entry

  • Presents the user with a single input text field

Example:

text = StringVar(self, 'placeholder text')
entry = Entry(textvariable=text)

Button

Example:

button = Button(text="Click me!", command=self.on_click)

on_click is the name of the function defined inside our class, and this function gets executed whenever the button is clicked.

Other common optional arguments

  • padx
  • pady
  • relief ('FLAT', 'RAISED', 'SUNKEN', 'GROOVE', or 'RIDGE')
  • borderwidth

Check Button

The following is an example of creating two check buttons, with text label "male" and "female", where the function on_check will be called every time there is a value change on either of the check buttons.

Example:

self.male = IntVar()
cb1 = Checkbutton(text="male", variable=self.var1, command=self.on_check)
self.female = IntVar()
cb2 = Checkbutton(text="female", variable=self.var2, command=self.on_check)

def on_check():
    # value will be 1 if checked, else 0
    print("male:", self.male.get())
    print("female:", self.female.get())

Radio Button

The following is an example of creating three radio buttons, with text label "home", "office" and "mobile", where the function on_select will be called every time there is a value change on any of the radio buttons.

Example:

self.phone = StringVar(self, 'home')  # home will be checked by default
Radiobutton(text='Home', variable=self.phone, value='home', command=self.on_select).grid(row=0)
Radiobutton(text='Office', variable=self.phone, value='office', command=self.on_select).grid(row=1)
Radiobutton(text='Mobile', variable=self.phone, value='cell', command=self.on_select).grid(row=2)

def on_select(self):
    # value will be 'home', 'office', or 'cell'
    print(self.phone.get())

Combo Box

Example:

from tkinter.ttk import Combobox

self.day = StringVar()
day = Combobox(self, width=27, textvariable=self.month)
day['values'] = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
day.grid(column=1, row=1)
day.current()

Wrapping Up

Now, we will need to instantiate our Application class and run it.

Event Loop for Event-Driven Programming

  • When you have a graphical user interface, in order for the program to register events (e.g., a mouse hover event) it has to run on a continuous loop.
  • This loop will keep running until the program terminates
if __name__ == "__main__":
    app = Application()
    app.title('My First TKinter App')  # window title
    # this loop allows for event-driven programming
    app.mainloop()

And that's it! Simply run the program and you'll have a working GUI made with Python. Thanks for reading!