How to create an impressive GUI in Python using Tkinter?


Tkinter is a standard Python GUI library in Python, which gives us an object-oriented interface with Tk GUI Toolkit. It's amazing how quickly one can create some really impressive looking apps. Actions in GUI are usually performed through direct manipulation of graphical elements.

We will take a simple "addition" application to show how easy it is to create an impressive GUI in Python using tkinter. GUI is all about widgets and windows and these are available in Tkinter.

First, we will import the Tkinter library, then create a window object (class Tk is used to create window object) and create a label widget in which we can show any text or image (used in GUI application). The widget is in the insert window and on executing, we will get the output screen.

Example

# Import the required libraries
from tkinter import *
win=Tk()
win.geometry("700x300")

def sum():
   a=int(entry1.get())
   b=int(entry2.get())
   c=a+b
   # insert(index,value)
   entry3.insert(0,c)

def clearing():
   # delete(0,END)
   entry1.delete(0,END)
   entry2.delete(0,END)
   entry3.delete(0,END)

label1=Label(win, text="Enter number 1:", padx=20, pady=10)
label2=Label(win, text="Enter number 2:", padx=20, pady=10)

entry1=Entry(win, width=30, borderwidth=2)
entry2=Entry(win, width=30, borderwidth=2)
entry3=Entry(win, width=30, borderwidth=2)

add=Button(win, text="Add", padx=20, pady=10, command=sum)

clear=Button(win, text="Clear", padx=20, pady=10, command=clearing)

label1.grid(row=0, column=0)
label2.grid(row=1, column=0)

entry1.grid(row=0, column=1)
entry2.grid(row=1, column=1)
add.grid(row=2, column=0)
entry3.grid(row=3, column=0)
clear.grid(row=2, column=1)

win.mainloop()

Output

If we run the above code, it will display a window with a basic addition widget.

Now, insert two numbers (number 1 and number 2) and click the Add button to show the summation of number 1 and number 2 or click the Clear button to refresh the output screen.

Updated on: 22-Dec-2021

771 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements