Introduction to Python tkinter module

tkinter module:

tkinter module is used to create GUI or Graphical user interface applications in Python. tkinter stands for TK interface and it is used as an interface for the TK GUI toolkit. TK is not a part of python but both TK and tkinter are available in most Unix and windows machines.

In this post, we will learn how to create a basic project in tkinter to give you an idea of how it works.

Verify that you tkinter is working:

tkinter is already included with python. So, if you have python installed on your system, it will be there. Just open one terminal and run the below command to verify it:

python3 -m tkinter

or 

python -m tkinter

It will open one small window with the version of TK installed.

tkinter basic window

If this window is not opening, you might need to reinstall/update your python.

Writing your first tkinter module:

tkinter module is one of the most widely used GUI module in python. It is easy to use and it provides different widgets that can be used just right out of the box.

The UI elements are called widgets. In this post, we will create one text widget and add it to a basic tkinter project.

Create one python script with the below code:

from tkinter import *

main_window = Tk()

label = Label(main_window, text= "Hello World !!", width="20", height="20").pack()

main_window.mainloop()

Now, execute this script. It will give one output as like below:

python tkinter intro

Here,

  • main_window is the main window object that we created by using Tk().
  • label is the label to add to the main window. We are creating the Label by passing the main window to the Label constructor.
  • The last line is uses mainloop() which will show the final window and wait for the user to close it manually.

You might also like: