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
- Introduction
- What is Tkinter?
- Packaging methods
- Tinker widgets
- Final project- a simple calculator
- 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.
- Import the Tkinter module.
- Create the main application window.
- Add the widgets like labels, buttons, frames, etc. to the window.
- 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:
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.
- The pack() method
- The grid() method
- 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,
button | canvas | check button | entry |
list box | message box | radio button | scrolled text |
text | combo box | label | paned window |
menu | menu button | spin box | others |
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:
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
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:
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
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:
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:
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
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
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
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
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