GUI Python with Tkinter – Part 1 – Introduction to Tkinter and root window

Tkinter is a graphical user interface (GUI) library for Python. It is the Python interface to Tk, the GUI toolkit for Tcl/Tk.

Tcl (Tool Command Language) is a scripting language used in embedded applications, testing, prototyping, and GUI development. Tk is an open source, multi-platform widget toolkit for building GUI programs.

There are a few key concepts you must understand in order to be able to work with Tkinter and Python.

  • Understand the root window and the main loop
  • Understand widgets and how to use them (buttons, entry fields, checkboxes, radio buttons, scroll bars etc.
  • Understand geometry managers for creating layouts (the position and the structural layout of the components.
  • Understand the events and callbacks (interaction and behavior of the components; command and event bidings).
  • Understand how to style widgets

First of all you have to make sure you have Python and Tkinter installed on your machine. Python should be installed if you use Mac or Linux (in Windows can be installed). If you don’t have Tkinter installed you can install it by running the following command in the terminal:

sudo apt-get install python3-tk

Once the Tkinter is installed, start the Python server by typing the python3 in the terminal and check if Tkinter is installed in our machine.

>>> import tkinter
>>> tkinter._test()

If everything is fine you should have a window pop up on the screen.

Note:
You can import Tkinter using from tkinter import * or import tkinter as tk.

The first thing you have to do is to create the main window which is known as the root window. To do that you need the following lines of code placed in a .py file (I name my file test.py:

from tkinter import *
root = Tk()
root.mainloop()

Navigate in the terminal to the location where your file is saved (using the cd command) then run the following command:

python3 test.py

You should get a blank root window with the minimize, maximize, and close buttons, and a blank frame.

The first line imported all ( * ) the classes, attributes, and methods of Tkinter into the current workspace.
The second line created an instance of the tkinter.Tk class (basically the root window).
The third line executs the mainloop method of the root object to keep the root window visible.

Leave a Reply