Create UI in Python-Tkinter
Modern computer applications are user-friendly. User interaction is not restricted to console-based I/O. They have a more ergonomic graphical user interface (GUI) thanks to high speed processors and powerful graphics hardware. These applications can receive inputs through mouse clicks and can enable the user to choose from alternatives with the help of radio buttons, dropdown lists, and other GUI elements (or widgets).
Such applications are developed using one of various graphics libraries available. A graphics library is a software toolkit having a collection of classes that define a functionality of various GUI elements. These graphics libraries are generally written in C/C++. Many of them have been ported to Python in the form of importable modules. Some of them are listed below:
Tkinter is the Python port for Tcl-Tk GUI toolkit developed by Fredrik Lundh. This module is bundled with standard distributions of Python for all platforms.
PyQtis, the Python interface to Qt, is a very popular cross-platform GUI framework.
PyGTK is the module that ports Python to another popular GUI widget toolkit called GTK.
WxPython is a Python wrapper around WxWidgets, another cross-platform graphics library.
This tutorial explains the use of Tkinter in developing GUI-based Python programs.
Basic GUI Application
GUI elements and their functionality are defined in the Tkinter module. The following code demonstrates the steps in creating a UI.
from tkinter import *
window=Tk()
# add widgets here
window.title('Hello Python')
window.geometry("300x200+10+20")
window.mainloop()First of all, import the TKinter module. After importing, setup the application object by calling the Tk() function. This will create a top-level window (root) having a frame with a title bar, control box with the minimize and close buttons, and a client area to hold other widgets. The geometry() method defines the width, height and coordinates of the top left corner of the frame as below (all values are in pixels): window.geometry("widthxheight+XPOS+YPOS")The application object then enters an event listening loop by calling the mainloop() method. The application is now constantly waiting for any event generated on the elements in it. The event could be text entered in a text field, a selection made from the dropdown or radio button, single/double click actions of mouse, etc. The application's functionality involves executing appropriate callback functions in response to a particular type of event. We shall discuss event handling later in this tutorial. The event loop will terminate as and when the close button on the title bar is clicked. The above code will create the following window: