Graphical User Interface with tkinter python

by Apr 10, 2020Python Tkinter

In this article, we will tell about the GUI(graphical user interface) in python using. We should also know about how to import the library and using some widgets in it. Let’s have a quick look at the below contents.

Contents

  1. Introduction
  2. What is Tkinter?
  3. Packaging methods
  4. Tinker widgets
  5. Final project- a simple calculator
  6. Conclusion

1. Introduction

Graphical User Interface (GUI) is nothing but a desktop application that helps you to interact with the computers. They are generally used to perform an eclectic number of tasks on your computer or laptop.

  • GUI applications are generally like that of text editors that create, delete or append data in different types of files.
  • They are also used in small-time applications like making a  calculator, drawing, chess game.
  • They are also used in browsers like google chrome, Firefox.

We will learn how to open the Tkinter tab and add some widgets to it .

Python has a plethora of libraries and these 4 stands out mainly when it comes to GUI. There are as follows:

Among all of these, Tkinter is preferred by a lot of learners and developers just because of how simple and easy it is.


2. What is Tkinter?

Tkinter is actually an inbuilt Python module used to create simple GUI apps. It is the most commonly used module for GUI apps in Python.

You don’t need to worry about the installation of the Tkinter module as it comes with Python default. If you don’t have python itself get it here.

Developing desktop-based applications with python Tkinter is not a complex task. An empty Tkinter top-level window can be created by using the following steps.

  1. Import the Tkinter module.
  2. Create the main application window.
  3. Add the widgets like labels, buttons, frames, etc. to the window.
  4. Call the main event loop so that the actions can take place on the user’s computer screen.
from tkinter import* #importing tkinter 
root = Tk()  #creating and opening application window
root.title("gui")#giving title to the window
root.mainloop()  #enter mainloop event

Output:

Output – Tkinter GUI

3. Packaging methods

The Tkinter geometry specifies the method by using which, the widgets are represented on display. The python Tkinter provides the following geometry methods.

  1. The pack() method
  2. The grid() method
  3. The place() method

The most commonly used ones are the pack() method and the grid() methods these will be used further in the tutorial for better understanding refer layout management.

4. Tkinter widgets

There are 18 widgets in tkinter out of them 8 are basic and important,

buttoncanvas check buttonentry
list boxmessage boxradio buttonscrolled text
textcombo box labelpaned window
menumenu buttonspin boxothers
Tkinker widgets

These widgets are the reason that Tkinter is so popular. It makes it really easy to understand and use practically.

in this tutorial we will talk about basic tkinter widgets.

Label:

Label widget is used for creating texts and images and all of that but it is important to note that it has to be a single line definition only.

There are a number of things you can do to your label like you can change font, text colour, size, insert an image on a button using a label, call functions.

basic syntax for this code is label(master , text=’text you want to display’)

#code:

from tkinter import *
root = Tk() 
w = Label(root, text='label example',bg='blue',font='comic sans ms',fg='yellow') 
w.pack() 
root.mainloop() 

output:

output-label widgets

Button:

The button widget is very similar to the label widget.is used to add various types of buttons to the python application. We create a variable and use the widget syntax to define what the button has to say.

we can also customise our button we can pass commands ,functions,change size, etc

basic syntax for this code is tk.button(master,command=’function’,text=’if any’)

import tkinter as tk 
root = tk.Tk() 
root.title('button example') 
button = tk.Button(root, text='Stop', width=25, command=root.destroy) 
button.pack() 
root.mainloop() 

output

output-GUI button

Check button

To select any number of options by displaying a number of options to a user as toggle buttons.

just like other widgets you can customise even check boxes to get your desired settings like colour of check box or size of your text etc.

from tkinter import *
master = Tk()
 
def var_states():
   print("java: %d,\npython: %d" % (var1.get(), var2.get()))
 
Label(master, text="Your language:").grid(row=0, sticky=W)
var1 = IntVar()
Checkbutton(master, text="java", variable=var1).grid(row=1, sticky=W)
var2 = IntVar()
Checkbutton(master, text="python", variable=var2).grid(row=2, sticky=W)
Button(master, text='Quit', command=master.quit).grid(row=3, sticky=W, pady=4)
Button(master, text='Show', command=var_states).grid(row=4, sticky=W, pady=4)
mainloop()

output:

output-check button example

Entry:

It is used to input the single-line text entry from the user. For multi-line text input, a Text widget is used.

Just like how we can modify labels we can also modify entry widget.we can change foreground color, background color, call a function, change the font, focus, we can also change the color inside the entry box.

from tkinter import *
master = Tk() 
 
l1=Label(master, text='name').grid(row=0) 
l2=Label(master, text='grade').grid(row=1) 
e1 = Entry(master) 
e2 = Entry(master) 
e1.grid(row=0, column=1) 
e2.grid(row=1, column=1) 
def show_entry_fields1():
    ll1=Label(master,text="First Name:" + e1.get())
    ll1.grid(row=3)
def show_entry_fields():
    ll2=Label(master,text="grade" + e2.get())
    ll2.grid(row=4)
 
 
bt1=Button(master,text="Enter",command=show_entry_fields1).grid(row=0,column=2)
bt2=Button(master,text="enter",command=show_entry_fields).grid(row=1,column=2)
mainloop() 

here we are using both button widget and entry widget in this example

output-GUI entry widget example

Radio button

It is used to offer a multi-choice option to the user. It offers several options to the user and the user has to choose one option. unlike a checkbox, the user cannot choose two options.

so it is like a multiple choice question with only one answer

from tkinter import *  
  
def language():  
   selection = "Your favourite programming language is  " + str(radio.get())  
   label.config(text = selection)  
  
top = Tk()  
top.geometry("300x150")  
radio = IntVar()  
lbl = Label(text = "Favourite programming language:")  
lbl.pack()  
R1 = Radiobutton(top, text="C", variable=radio, value=1,command=language)  
R1.pack( anchor = W )  
  
R2 = Radiobutton(top, text="C++", variable=radio, value=2,command=language)  
R2.pack( anchor = W )  
  
R3 = Radiobutton(top, text="Java", variable=radio, value=3,command=language)  
R3.pack( anchor = W) 

R4=Radiobutton(top,text="python" ,variable=radio,value=4,command=language)
R4.pack(anchor=W) 
label = Label(top)  
label.pack()  
top.mainloop() 

output:

output-radio button example

Combo box

combo box is just like a menu widget and has a drop down menu with certain options.

you can use below code for reference for combo box.

import tkinter as tk 
from tkinter import ttk
window = tk.Tk() 
window.title('Combobox') 
window.geometry('500x250') 
ttk.Label(window, text = "Combobox Widget example",  
          background = 'yellow', foreground ="red",  
          font = ("comic sans ms", 15)).grid(row = 0, column = 1) 
ttk.Label(window, text = "select your language :", 
          font = ("symbol", 10)).grid(column = 0, row = 5, padx = 10, pady = 25) 
 
n = tk.StringVar() 
languagechoosen = ttk.Combobox(window, width = 27, textvariable = n) 
languagechoosen['values'] = ('python','perl','ruby','c','c++','java','php','angular') 
languagechoosen.grid(column = 1, row = 5) 
languagechoosen.current() 
s=tk.Button(window,text="ok",)
window.mainloop() 

output:

output-GUI combo widget example

Scrolled text

It is a Scrolled Text widget in a Python GUI application. It will display the scrolled text area on the application screen. 

you can use the below code for reference

from tkinter import ttk  
from tkinter import scrolledtext  
win = tk.Tk()  
win.title("scroll text")  
ttk.Label(win, text="This is Scrolled Text Area").grid(column=0,row=0)  
scrolW=30  
scrolH=2  
scr=scrolledtext.ScrolledText(win, width=scrolW, height=scrolH, wrap=tk.WORD)  
scr.grid(column=0, columnspan=3)  
win.mainloop()  

output

output-GUI scrolled text example

Canvas

The canvas widget is used to add the structured graphics to the python application. It is used to draw the graph and plots to the python application. The syntax to use the canvas is given below.

w = canvas(parent, options)  

from tkinter import *   
  
top = Tk()  
  
top.geometry("300x200")  
  
#creating a simple canvas  
c = Canvas(top,bg = "sea green",height = "200")  
  
  
c.pack()  
  
top.mainloop()  

output:

List box

The Listbox widget is used to display the list items to the user. We can place only text items in the Listbox and all text items contain the same font and color.

The user can choose one or more items from the list depending upon the configuration.

from tkinter import *  
  
top = Tk()  
  
top.geometry("200x250")  
  
lbl = Label(top,text = "best programming languages")  
  
listbox = Listbox(top)  
  
listbox.insert(1,"python")  
  
listbox.insert(2, "c")  
  
listbox.insert(3, "c++")  
  
listbox.insert(4, "c#") 
  
lbl.pack()  
listbox.pack()  
  
top.mainloop()  

output

Message box

The message box module is used to display the message boxes in the python applications. Various functions are used to display the relevant messages depending upon the application requirements.

For further insight in this widget refer here

Text

The Text widget is used to show the text data on the Python application. However, Tkinter provides us the Entry widget which is used to implement the single line text box.

The Text widget is used to display the multi-line formatted text with various styles and attributes. The Text widget is mostly used to provide the text editor to the user.It is just like scrolled text .

from tkinter import *  
  
top = Tk()  
text = Text(top)  
text.insert(INSERT, "Name.....")  
text.insert(END, "coding language.....")  
  
text.pack()  
  
text.tag_add("Write Here", "1.0", "1.4")  
text.tag_add("Click Here", "1.8", "1.13")  
  
text.tag_config("Write Here", background="yellow", foreground="black")  
text.tag_config("Click Here", foreground="red")  
  
top.mainloop()  

output

Spin box

The Spinbox widget is an alternative to the Entry widget. It provides the range of values to the user, out of which, the user can select the one.

It is used in the case where a user is given some fixed number of values to choose from.

For further insight in this widget refer here

Paned window

The PanedWindow widget acts like a Container widget which contains one or more child widgets (panes) arranged horizontally or vertically. The child panes can be resized by the user, by moving the separator lines known as sashes by using the mouse.

Each pane contains only one widget. The PanedWindow is used to implement the different layouts in the python applications.

For further insight in this widget refer here

Menu:

The Menu widget is used to create various types of menus (top level, pull down, and pop up) in the python application.

The top-level menus are the one which is displayed just under the title bar of the parent window. We need to create a new instance of the Menu widget and add various commands to it by using the add() method.

For further insight in this widget refer here

Menu button

The Menubutton widget can be defined as the drop-down menu that is shown to the user all the time. It is used to provide the user a option to select the appropriate choice exist within the application.

The Menu button is used to implement various types of menus in the python application. A Menu is associated with the Menu button that can display the choices of the Menu button when clicked by the user.

It is like a list box with commands integrated with it.

for further insight click here

Others

There three other widgets remaining in tkinter

Frame

Python Tkinter Frame widget is used to organise the group of widgets. It acts like a container which can be used to hold the other widgets. The rectangular areas of the screen are used to organise the widgets to the python application.

for further insight refer second part of this python GUI tutorial here

Scale

The Scale widget is used to implement the graphical slider to the python application so that the user can slide through the range of values shown on the slider and select the one among them.

We can control the minimum and maximum values along with the resolution of the scale. It provides an alternative to the Entry widget when the user is forced to select only one value from the given range of values.

from tkinter import *  
  
def select():  
   sel = "Value = " + str(v.get())  
   label.config(text = sel)  
     
top = Tk()  
top.geometry("200x100")  
v = DoubleVar()  
scale = Scale( top, variable = v, from_ = 1, to = 50, orient = HORIZONTAL)  
scale.pack(anchor=CENTER)  
  
btn = Button(top, text="Value", command=select)  
btn.pack(anchor=CENTER)  
  
label = Label(top)  
label.pack()  
  
top.mainloop()  

output

output-GUI scale

Top-level

The Toplevel widget is used to create and display the toplevel windows which are directly managed by the window manager. The toplevel widget may or may not have the parent window on the top of them.

The toplevel widget is used when a python application needs to represent some extra information, pop-up, or the group of widgets on the new window.

The top-level windows have the title bars, borders, and other window decorations.

from tkinter import *  
  
root = Tk()  
  
root.geometry("200x200")  
  
def open():  
    top = Toplevel(root)  
    top.mainloop()  
  
btn = Button(root, text = "open", command = open)  
  
btn.place(x=75,y=50)  
  
root.mainloop()  

output

output-GUI top level

Final project-a simple calculator

Now, you can do this in a lot of ways .so I suggest you don’t copy down my code

Every GUI apps include two steps:

  • Creating a User Interface
  • Adding functionalities to the GUI

from tkinter import *
# creating basic window
window = Tk()
window.geometry("312x324") # size of the window width:- 500, height:- 375
window.resizable(0, 0) # this prevents from resizing the window
window.title("Calcualtor")
# 'btn_click' function continuously updates the input field whenever you enters a number
def btn_click(item): 
    global expression
    expression = expression + str(item)
    input_text.set(expression)
# 'btn_clear' function clears the input field
def btn_clear():
    global expression
    expression = ""
    input_text.set("")
# 'btn_equal' calculates the expression present in input 
def btn_equal():
    global expression
    result = str(eval(expression)) # 'eval' function evalutes the string expression directly
    # you can also implement your own function to evalute the expression istead of 'eval' function
    input_text.set(result)
  exression = ""
expression = ""
# 'StringVar()' is used to get the instance of the input field
input_text = StringVar()
 # creating a frame for the input field
 input_frame = Frame(window, width = 312, height = 50, bd = 0, highlightbackground = "black", highlightcolor = "black", highlightthickness = 1)
input_frame.pack(side = TOP)
# creating an input field inside the 'Frame'
input_field = Entry(input_frame, font = ('arial', 18, 'bold'), textvariable = input_text, width = 50, bg = "#eee", bd = 0, justify = RIGHT)
 input_field.grid(row = 0, column = 0)
input_field.pack(ipady = 10) # 'ipady' is internal padding to increase the height of input field
 # creating another 'Frame' for the button below the 'input_frame'
 btns_frame = Frame(window, width = 312, height = 272.5, bg = "grey")
btns_frame.pack()
# first row
 clear = Button(btns_frame, text = "C", fg = "black", width = 32, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_clear()).grid(row = 0, column = 0, columnspan = 3, padx = 1, pady = 1)
divide = Button(btns_frame, text = "/", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("/")).grid(row = 0, column = 3, padx = 1, pady = 1)
 # second row
 seven = Button(btns_frame, text = "7", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(7)).grid(row = 1, column = 0, padx = 1, pady = 1)
 eight = Button(btns_frame, text = "8", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(8)).grid(row = 1, column = 1, padx = 1, pady = 1)
 nine = Button(btns_frame, text = "9", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(9)).grid(row = 1, column = 2, padx = 1, pady = 1)
 multiply = Button(btns_frame, text = "*", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("*")).grid(row = 1, column = 3, padx = 1, pady = 1)
 # third row
 four = Button(btns_frame, text = "4", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1)
 five = Button(btns_frame, text = "5", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(5)).grid(row = 2, column = 1, padx = 1, pady = 1)
 six = Button(btns_frame, text = "6", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(6)).grid(row = 2, column = 2, padx = 1, pady = 1)
 minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("-")).grid(row = 2, column = 3, padx = 1, pady = 1)
 # fourth row
 one = Button(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1, pady = 1)
 two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady = 1)
 three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(3)).grid(row = 3, column = 2, padx = 1, pady = 1)
 plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("+")).grid(row = 3, column = 3, padx = 1, pady = 1)
 # fourth row
 zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(0)).grid(row = 4, column = 0, columnspan = 2, padx = 1, pady = 1)
 point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click(".")).grid(row = 4, column = 2, padx = 1, pady = 1)
 equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_equal()).grid(row = 4, column = 3, padx = 1, pady = 1)
 window.mainloop()

In the above example I only showed one of many possible ways of creating a calculator you can also try to make it look little different like adding colours or adding menu button or can even use top level to show your result in another window in a similar way you can also work on similar projects to this one to improve your understanding about python GUI

output

output-GUI calculator

Conclusion

The concepts discussed in this tutorial should help you make your own GUI apps and add functionality to the same.

This will be very handy when you are trying to create a customized application with a GUI that is suited for your personal needs. Now, you should also be able to use these widgets and images to develop applications easily with the help of Python.

This article is first part of python GUI tutorial seris in next part you will learn about layout mangement

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

Data And Classes in Python Tkinter

Data And Classes in Python Tkinter

In this article, we are going to learn about data and classes in python Tkinter. We will save our GUIdata into Tkinter variables after that we will also start using OOP to extend the existing Tkinter classes to extend the built-in functionality of Tkinter....

Python Tkinter MessageBox-Example

Python Tkinter MessageBox-Example

INTRODUCTION In this article, we will learn “How to interface the radio button and messages with Tkinter”. I recommend you to go through this first similarly if you are new to Tkinter go through this. Here we will design a GUI with a 4 radio button and...

asksaveasfile() function in Python-Tkinter

asksaveasfile() function in Python-Tkinter

In this tutorial, we will be learning how to use the asksaveasfile() in Tkinter and save the file in the system. The asksaveasfile() function comes under the class filedialog. The file dialog module provides functions for creating file/directory selection...

Plotting graphs with Matplotlib (Python)

Plotting graphs with Matplotlib (Python)

In this tutorial, you'll learn about matplotlib, the plotting library of Python. You'll also get to learn how do we use it for plotting different types of graphs in Python. What is Matplotlib? Matplotlib is an amazing visualization library in Python for 2D plots of...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....