0% found this document useful (0 votes)
31 views

Tkinter

The document discusses different GUI widgets available in Tkinter like labels, buttons, text entry boxes, dropdown menus and checkboxes. It explains how to create each widget and handle basic interactions with them.

Uploaded by

susan babu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Tkinter

The document discusses different GUI widgets available in Tkinter like labels, buttons, text entry boxes, dropdown menus and checkboxes. It explains how to create each widget and handle basic interactions with them.

Uploaded by

susan babu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Graphical User Interface (GUI) is nothing but a desktop application which helps you

to interact with the computers. They perform different tasks in the desktops, laptops
and other electronic devices.
 GUI apps like Text-Editors create, read, update and delete different types of
files.
 Apps like Sudoku, Chess and Solitaire are games which you can play.
 GUI apps like Google Chrome, Firefox and Microsoft Edge browse through
the Internet.
They are some different types of GUI apps which we daily use on the laptops or
desktops.
Python Libraries To Create Graphical User Interfaces:
Python has a plethora of libraries and these 4 stands out mainly when it comes to
GUI. There are as follows:
 Kivy
 Python QT
 wxPython
 Tkinter
Among all of these, Tkinter is the first choice for a LOT of learners and developers
just because of how simple and easy it is.
Tkinter is actually an inbuilt Python module used to create simple GUI apps. It is the
most commonly used module for GUI apps in the Python.
Fundamentals Of Tkinter
Consider the following diagram, it shows how an application actually executes in
Tkinter:

To start out with, we first import the Tkinter model. Followed by that, we create the
main window. It is in this window that we are performing operations and displaying
visuals and everything basically. Later, we add the widgets and lastly we enter the
main event loop.
If you noticed, there are 2 keywords here that you might not know at this point.
These are the 2 keywords:
 Widgets
 Main Event Loop
An event loop is basically telling the code to keep displaying the window until we
manually close it. It runs in an infinite loop in the back-end.
Check out the following code for better clarity:
1 import tkinter

3 window = tkinter.Tk()

4
5 # to rename the title of the window window.title("GUI")

7 # pack is used to show the object in the window

9 label = tkinter.Label(window, text = "Hello World!").pack()

10

11 window.mainloop()

As you can see, we are importing the Tkinter package and defining a window.
Followed by that, we are giving a window title which is shown on the title tab
whenever you open an application.
For example, Microsoft Word is shown on the title tab when you open a word
application, Similarly here we call it GUI. We can call it anything we want based on
the requirement.
Lastly, we have a label. A label is nothing but what output needs to be shown on the
window. In this case as you can already see, it is hello world.
Check out the output for the above code:

Next up on this Tkinter tutorial blog, let us look at the massive range of widgets
offered by Tkinter.

Tkinter Widgets

Widgets are something like elements in the HTML. You will find different types
of widgets to the different types of elements in the Tkinter.
Let’s see the brief introduction to all of these widgets in the Tkinter.
Check out this diagram for the list of the majorly used Tkinter widgets:

 Canvas – Canvas is used to draw shapes in your GUI.


 Button – Button widget is used to place the buttons in the Tkinter.
 Checkbutton – Checkbutton is used to create the check buttons in your application.
Note that you can select more than one option at a time.
 Entry – Entry widget is used to create input fields in the GUI.
 Frame – Frame is used as containers in the Tkinter.
 Label – Label is used to create a single line widgets like text, images etc.
 Menu – Menu is used to create menus in the GUI.
These widgets are the reason that Tkinter is so popular. It makes it really easy to
understand and use practically.
The first widget we will be checking out is the label widget.

Label Widget:

Labels are used to create texts and images and all of that but it is important to note
that it has to be a single line definition only.
Here’s the code snippet:
1 l1 = Label (window, text="edureka!“ font=("Arial Bold", 50))

3 l1.grid (column=0, row=0)

Check out the output below:

There is something called as the geometry function. It is basically used to change


the window size and set as per our requirement.
Check out the code snippet below:
1 l1 = Label (window, text="edureka!“ font=("Arial Bold", 50))

3 window.geometry('350x200')

5 l1.grid (column=0, row=0)

We have set it to be 350 pixels in width and 200 pixels in height.


And here is the output for the same:
The next widget we will check on this Tkinter tutorial blog is the button widget.

Programming Certification Training


Explore Curriculum

Button Widget:
The button widget is very similar to the label widget. We create a variable and use
the widget syntax to define what the button has to say.
Check out the below code snippet:
1 bt = Button (window, text="Enter")

3 bt.grid (column=1, row=0)

Here, we used a function called as the grid function which is used to set the position
of the button on our window.
The output of the code is as follows:

We can also change the foreground for a button or any other widget as well. We will
be using the parameter FG as shown in the code. Similarly, the background colour
can be changed as well using the BG property.
Check out the code:
1 bt = Button (window, text="Enter", bg="orange", fg="red")

3 bt.grid (column=1, row=0)

Output:

As per the output we got, our foreground is the text which is red color as defined and
the background is orange as we’ve set it using the bg parameter.
So at this point, we have a clickable button. Well, what happens when we actually go
ahead and click it?
Check out this snippet:
1 def clicked():

3 l1.configure (text="Button was clicked !!")

5 bt = Button (window, text=“Enter”, command=clicked)

So we call this the click event. We need to write the functionality as to what should
happen when we click the button or in other terms when the click event is fired.
For that purpose we have a function called clicked, we are displaying a text message
saying button was clicked.
We will need to add a parameter called command in the button definition as shown.
Pretty easy, right?
The next widget we will check on this Tkinter tutorial blog is the entry widget.
Entry Widget:
What is an entry widget used for?
It is used to create input fields in the GUI to take in textual input.
Check out the example code shown below:
1 txt = Entry(window,width=10)

3 txt.grid(column=1, row=0)

4
def clicked():
5

6
res = "Welcome to " + txt.get()
7

8
l1.configure(text= res)
9

10
bt = Button (window, text=“Enter”, command=clicked)
11

Here, we are creating a textbox using the Tkinter entry class. The grid tells the code
where we want the widget on the window.
What should happen when the button is clicked?
Well, we have a message that says ‘Welcome to’ and later whatever is input into the
text area will be concatenated along with this and printed.
Check out the output. We’ve typed Python Training and so it displays welcome to
python training.
Output:

All these widgets are really simple and more than that they always come in handy as
well.
The next widget we will check on this Tkinter tutorial blog is the combobox widget.
Combobox Widget
Can you take a quick guess on what a combobox widget is?
Well, it is just a drop-down menu with certain options.
Here’s the code snippet:
1 from tkinter.ttk import *
2 combo = Combobox(window)

3 combo['values']= (1, 2, 3, 4, 5, "Text")

4 combo.current(3)

combo.grid(column=0, row=0)
5

So check out that there are no other parameters for the combobox definition apart
from the window. And in the next line, we have defined certain values such numbers
ranging from 1 to 5 and next, we have text. 1 to 5 were numeric inputs but we can
have a textual input too.
It is defined using double quotes and we later will set the selected input. Followed by
that, we have the grid function to place the widget on the window.
So we have the drop-down menu and it displays all that we’ve defined in the code.
Here is the output for the code:

Another easy widget, done!


The next widget we will check on this Tkinter tutorial blog is the Checkbutton widget.
Checkbutton Widget:
The checkbutton is widely used in almost all the sites.
So basically we use the checkbutton class to create the widget.
Code snippet:
1 chk_state = BooleanVar()

2 chk_state.set (True)

3 chk = Checkbutton(window, text=‘Select', var=chk_state)

4 chk.grid(column=0, row=0)

We start by creating a variable of the type booleanvar.


But this is not a standard python variable, correct? Well nothing to worry, this is a
Tkinter variable.
By default, we keep the set state to be true which means that the button is checked
already. And next, we are passing chk_state to the checkbutton class to set the
check state for us.
Output:

Check out the above output. So we have a really simple checkbutton widget with a
certain text.
So what other easy widgets like these are available?
The next widget we will check on this Tkinter tutorial blog is the radio button widget.
Radio Button Widget:
The radio button widget is quite popular and I can give you a guarantee that you
have seen and used this widget before.
We will use the radiobutton class to add the widget.
Take a look at the code:
1 rad1 = Radiobutton(window, text=Python', value=1)
2 rad2 = Radiobutton(window, text=Java', value=2)

3 rad3 = Radiobutton(window, text=Scala', value=3)

4 rad1.grid(column=0, row=0)

5 rad2.grid(column=1, row=0)

rad3.grid(column=2, row=0)
6

Here, we have the value parameters to be different. 1,2 and 3. However, if they are
same, it will lead to conflict and there will be an error. So it is to be noted that a
unique value is used to address the radio buttons.
The value should be unique but the textual data can be the same, however. Here we
have considered Python, Java, and Scala. It can be whatever you want it to be
based on the requirements.
Data Science Training

DATA SCIENCE CERTIFICATION TRAINING WITH PYTHON


Data Science Certification Training with Python
Reviews

5(86329)

PYTHON PROGRAMMING CERTIFICATION TRAINING


Python Programming Certification Training
Reviews

5(23531)

MACHINE LEARNING CERTIFICATION TRAINING


Machine Learning Certification Training
Reviews

5(10313)
DATA SCIENCE CERTIFICATION COURSE USING R
Data Science Certification Course using R
Reviews

5(37663)

DATA ANALYTICS WITH R CERTIFICATION TRAINING


Data Analytics with R Certification Training
Reviews

5(24060)

STATISTICS ESSENTIALS FOR ANALYTICS


Statistics Essentials for Analytics
Reviews

5(5691)

SAS TRAINING AND CERTIFICATION


SAS Training and Certification
Reviews

5(4589)

ANALYTICS FOR RETAIL BANKS


Analytics for Retail Banks
Reviews

5(1260)

ADVANCED PREDICTIVE MODELLING IN R CERTIFICATION TRAINING


Advanced Predictive Modelling in R Certification Training
Reviews
4(3750)

Next

Similarly, the grid function used to place the widget on the window.
Output:

From the above output, do note that unlike a checkbutton where you can try
selecting multiple, here in case of radio button you can only select one at a time.
The next widget we will check on this Tkinter tutorial blog is the scrolled text widget.
Scrolled Text Widget:
Another nice widget we have is the scrolled text widget. This can be added using the
scrolled text class.
Code:
1 from tkinter import scrolledtext

2 txt = scrolledtext.ScrolledText(window, width=40,height=10)

One thing you must note here which is very important is that you need to specify the
width and the height of the scrolled text widget. Well if we do not specify the same,
the entire window is filled up.
You can set the scrolled text content by using the insert method. The syntax is pretty
simple. We need to use txt.insert with the message as a parameter.
Output:

The next widget we will check on this Tkinter tutorial blog is the message box widget.
Message Box Widget:
Let us quickly walk through this simple widget. We are using the messagebox library
here as well.
Code:
1 from tkinter import messagebox

2 messagebox.showinfo('Message title’, 'Message content')

Importing the library and displaying the message. But we need to define the
message title and the message content here.
See, this is where things get interesting. Look at the snippet below:
1 def clicked():

2 messagebox.showinfo('Message title', 'Message content')

4 btn = Button(window,text=‘ENTER', command=clicked)

Here we have made use of two of the widgets we learnt. We are using a button click
to show a message box for us.
Here’s the output:

Pretty easy, right?


Last but not least, we will check out the Spinbox widget on this Tkinter tutorial.
SpinBox Widget:
Spinbox is a popular widget as well. There are two tabs, the up and down scroll tabs
present. This is how it differs from the scroll down widget. Here the static number will
change over a certain range of values.
Code:
1 spin = Spinbox(window, from_=0, to=100, width=5)

We have 3 parameters – from, to and width. From – tells the start and the default
value of the range and to – gives us the upper threshold of the range.
Width is basically to set the size of the widget to 5 character spaces. But since are
doing 0 to 100, 3 is sufficient for us but I have gone ahead and put 5 just so it looks
well placed.
You can put whatever you want here and it’s valid but make sure it is more than what
the range can offer.
Output:
And that’s a wrap to the majorly used widgets in Tkinter.
Next up on this Tkinter tutorial blog, we need to check out geometry management.

Geometry Management
All widgets in the Tkinter will have some geometry measurements. These
measurements give you to organize the widgets and their parent frames, windows
and so on.
Tkinter has the following three Geometry Manager classes.
 pack():- It organizes the widgets in the block, which mean it occupies the entire
available width. It’s a standard method to show the widgets in the window.
 grid():- It organizes the widgets in table-like structure.
 place():- It places the widgets at a specific position you want.
We already looked at the grid in almost all of the previous codes. If you have any
doubts, head to the comment section and leave a comment, let’s interact there.
Next up on this Tkinter tutorial blog, we need to check out how we can organize
layouts and widgets.

Organizing Layouts And Widgets


To arrange the layout in the window, we will use Frame, class. Let’s create a simple
program to see how the Frameworks.
Steps:-
 Frame creates the divisions in the window. You can align the frames as you like
with side parameter of pack() method.
 Button creates a button in the window. It takes several parameters like text (Value of
the Button), fg (Color of the text), bg (Background color)
Note – The parameter of any widget method must be where to place the widget.
In the below code, we use to place in the window, top_frame, bottom_frame.
1 import tkinter

2 window = tkinter.Tk()

window.title("GUI")
3
# creating 2 frames TOP and BOTTOM
4
top_frame = tkinter.Frame(window).pack()
5
bottom_frame = tkinter.Frame(window).pack(side = "bottom")
6
# now, create some widgets in the top_frame and bottom_frame

btn1 = tkinter.Button(top_frame, text = "Button1", fg =


"red").pack()# 'fg - foreground' is used to color the contents
7
btn2 = tkinter.Button(top_frame, text = "Button2", fg =
8 "green").pack()# 'text' is used to write the text on the Button
9 btn3 = tkinter.Button(bottom_frame, text = "Button2", fg =
"purple").pack(side = "left")# 'side' is used to align the widgets
10
btn4 = tkinter.Button(bottom_frame, text = "Button2", fg =
11
"orange").pack(side = "left")
12 window.mainloop()

Above code produces the following window, if you didn’t change the above code.

See the below example to get an idea of how it works.


import tkinter

window = tkinter.Tk()
1
window.title("GUI")
2
# creating 2 text labels and input labels
3
tkinter.Label(window, text = "Username").grid(row = 0) # this is
4 placed in 0 0

5 # 'Entry' is used to display the input-field

6 tkinter.Entry(window).grid(row = 0, column = 1) # this is placed in


0 1
7
tkinter.Label(window, text = "Password").grid(row = 1) # this is
8 placed in 1 0

tkinter.Entry(window).grid(row = 1, column = 1) # this is placed in


9 1 1
10 # 'Checkbutton' is used to create the check buttons
11 tkinter.Checkbutton(window, text = "Keep Me Logged
In").grid(columnspan = 2) # 'columnspan' tells to take the width of
12 2 columns
13 # you can also use 'rowspan' in the similar manner

window.mainloop()

You will get the following output:

Next up on this Tkinter tutorial blog, we need to check out a concept called binding
functions.
Binding Functions
Calling functions whenever an event occurs refers to a binding function.
 In the below example, when you click the button, it calls a function called say_hi.
 Function say_hi creates a new label with the text Hi.
1 import tkinter
2 window = tkinter.Tk()
3 window.title("GUI")

4 # creating a function called say_hi()

5 def say_hi():

6
tkinter.Label(window, text = "Hi").pack()
7
tkinter.Button(window, text = "Click Me!", command = say_hi).pack()
8 # 'command' is executed when you click the button
9 # in this above case we're calling the function 'say_hi'.

10 window.mainloop()

The above program will produce the following results:

Another way to bind functions is by using events. Events are something


like mousemove, mouseover, clicking, and scrolling.
The following program also produces the same output as the above one:
1 import tkinter

2 window = tkinter.Tk()

window.title("GUI")
3
# creating a function with an arguments 'event'
4
def say_hi(event): # you can rename 'event' to anything you want
5

6
7 tkinter.Label(window, text = "Hi").pack()

btn = tkinter.Button(window, text = "Click Me!")


8
btn.bind("Button-1", say_hi) # 'bind' takes 2 parameters 1st is
9 'event' 2nd is 'function'
10 btn.pack()
11 window.mainloop()

 ‘<Button-1>‘ parameter of bind method is the left clicking event, i.e., when you click
the left button the bind method call the function say_hi
o <Button-1> for left click
o <Button-2> for middle click
o <Button-3> for right click
 Here, we are binding the left click event to a button. You can bind it to any
other widget you want.
 You will have different parameters for different events
Clicking events are of 3 different types namely leftClick, middleClick,
and rightClick.

Python Programming Certification Training


Weekday / Weekend BatchesSee Batch Details

Now, you will learn how to call a particular function based on the event that occurs.
 Run the following program and click the left, middle, right buttons to calls a
specific function.
 That function will create a new label with the mentioned text.
1 import tkinter
2 window = tkinter.Tk()
3 window.title("GUI")

4 #creating 3 different functions for 3 events

5 def left_click(event):

6
tkinter.Label(window, text = "Left Click!").pack()
7
def middle_click(event):
8

9
10 tkinter.Label(window, text = "Middle Click!").pack()
11 def right_click(event):
12

13 tkinter.Label(window, text = "Right Click!").pack()

14 window.bind("Button-1", left_click)

15 window.bind("Button-2", middle_click)

window.bind("Button-3", right_click)
16
window.mainloop()
17

If you run the above program, you will see a blank window. Now, click the left,
middle and right button to call respective functions.
You get the something similar results to the following:

Next up on this Tkinter tutorial blog, we need to check out how we can add images to
our window.

Images And Icons


You can add Images and Icons using PhotoImage method.
Let’s how it works:
1 import tkinter

2 window = tkinter.Tk()

window.title("GUI")
3
# taking image from the directory and storing the source in a
4 variable
5 icon = tkinter.PhotoImage(file = "images/edureka.png")

6 # displaying the picture using a 'Label' by passing the 'picture'


variriable to 'image' parameter
7
label = tkinter.Label(window, image = icon)
8
label.pack()
9 window.mainloop()

You can see the icon in the GUI:

Now, you’re able to:-


 Understand the Tkinter code.
 Create frames, labels, buttons, binding functions, events and all.
 To develop simple GUI apps.
So next up on this Tkinter Tutorial blog, we’re going to create a simple Calculator
GUI with all the stuff that we’ve learned till now.

Use – Case : Calculator App Using Tkinter


Every GUI apps include two steps:
 Creating User Interface
 Adding functionalities to the GUI
1 from tkinter import *
2 # creating basic window
3 window = Tk()

4 window.geometry("312x324") # size of the window width:- 500,


height:- 375
5
window.resizable(0, 0) # this prevents from resizing the window
6
window.title("Calcualtor")
7 ################################### functions
######################################
8
# 'btn_click' function continuously updates the input field
9 whenever you enters a number
10 def btn_click(item):

11

12 global expression

13

14 expression = expression + str(item)

15

16 input_text.set(expression)

# 'btn_clear' function clears the input field


17
def btn_clear():
18

19
20 global expression

21

22 expression = ""

23
input_text.set("")
24

25
# 'btn_equal' calculates the expression present in input field
26

27
def btn_equal():
28

29
global expression
30

31
result = str(eval(expression)) # 'eval' function evalutes the
32 string expression directly

33
# you can also implement your own function to evalute the
34
expression istead of 'eval' function
35

36 input_text.set(result)
37

38 expression = ""

39

40 expression = ""

41

42 # 'StringVar()' is used to get the instance of input field

43

44 input_text = StringVar()

45
# creating a frame for the input field
46

47
input_frame = Frame(window, width = 312, height = 50, bd = 0,
48
highlightbackground = "black", highlightcolor = "black",
49 highlightthickness = 1)

50
51 input_frame.pack(side = TOP)

52

53 # creating a input field inside the 'Frame'

54
input_field = Entry(input_frame, font = ('arial', 18, 'bold'),
55
textvariable = input_text, width = 50, bg = "#eee", bd = 0, justify =
56 RIGHT)

57

58 input_field.grid(row = 0, column = 0)

59
input_field.pack(ipady = 10) # 'ipady' is internal padding to
60
increase the height of input field
61

62 # creating another 'Frame' for the button below the 'input_frame'


63

64 btns_frame = Frame(window, width = 312, height = 272.5, bg = "grey")

65

66 btns_frame.pack()

67

68 # first row

69
clear = Button(btns_frame, text = "C", fg = "black", width = 32,
70
height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda:
71 btn_clear()).grid(row = 0, column = 0, columnspan = 3, padx = 1, pady
= 1)
72

73
divide = Button(btns_frame, text = "/", fg = "black", width = 10,
74
height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda:
75 btn_click("/")).grid(row = 0, column = 3, padx = 1, pady = 1)

76

77 # second row

78
seven = Button(btns_frame, text = "7", fg = "black", width = 10,
79
height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
80 btn_click(7)).grid(row = 1, column = 0, padx = 1, pady = 1)

81
82

83 eight = Button(btns_frame, text = "8", fg = "black", width = 10,


height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
84 btn_click(8)).grid(row = 1, column = 1, padx = 1, pady = 1)
85

86 nine = Button(btns_frame, text = "9", fg = "black", width = 10,


height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
87
btn_click(9)).grid(row = 1, column = 2, padx = 1, pady = 1)
88

89
multiply = Button(btns_frame, text = "*", fg = "black", width = 10,
90 height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda:
btn_click("*")).grid(row = 1, column = 3, padx = 1, pady = 1)
91

92
# third row
93

94
four = Button(btns_frame, text = "4", fg = "black", width = 10,
95 height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1)
96

97
five = Button(btns_frame, text = "5", fg = "black", width = 10,
98
height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
99 btn_click(5)).grid(row = 2, column = 1, padx = 1, pady = 1)

100

101 six = Button(btns_frame, text = "6", fg = "black", width = 10, height


= 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
102 btn_click(6)).grid(row = 2, column = 2, padx = 1, pady = 1)
103

104 minus = Button(btns_frame, text = "-", fg = "black", width = 10,


height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda:
105
btn_click("-")).grid(row = 2, column = 3, padx = 1, pady = 1)
106

107
# fourth row
108

109 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()
Differences Between MongoDB and SQL
Server
There are basically two types of databases present: SQL and NoSQL. The

example of the SQL database is MySQL and NoSQL is MongoDB. MongoDB

stores the data in JSON like documents that can vary in structure offerings

a dynamic, flexible schema. MongoDB was also designed for high

availability and scalability with auto-sharding. SQL Server is a database

management and analysis system for e-commerce and data warehousing

solutions. MongoDB is one of the several databases that rise under the

NoSQL database which is used for high volume data storage. Instead of

using tables rows as Relational Database, MongoDB is based on the

architecture of collections and documents. In MongoDB, the rows (or

documents as called in MongoDB) don’t need to have a schema defined

beforehand. Instead, the fields can be created on the fly. The data model

available within MongoDB allows you to represent hierarchical


relationships, to store arrays, and other more complex structures more

easily.

MongoDB and SQL Server Comparision


Table
Below is the comparison table between MongoDB and SQL Server.

Base of Comparison MS SQL Server

Initial Release 1989 2009

Storage Model RDBMS Document-

Joins Yes No

Transaction ACID NO

Agile practices No Yes

Data Schema Fixed Dynamic

Scalability Vertical Horizontal

Map Reduce No Yes


Language SQL query language JSON Quer

Secondary index Yes Yes

Triggers Yes No

Foreign Keys Yes No

Concurrency Yes No

Company Name Microsoft MongoDB.I

License Commercial Open Sourc

Implementation Language C++ C++

Operating System Windows Windows, L

Drivers .NET, Java, PHP, Python, Ruby, Visual Basic Dart, Delph

Java, JavaSc

PHP, Power

Scala, Smal

Server-side scripts Transact SQL and .NET languages JavaScript’s


XML Support Yes No

Python SQL – How to use the SQLite, MySQL, and


PostgreSQL Databases with Python

Popular SQL Databases


SQLite
SQLite is best known for being an integrated database. This means
that you don't have to install an extra application or use a separate
server to run the database.

If you're creating an MVP or don't need a ton of data storage space,


you'll want to go with a SQLite database.

The pros are that you can move faster with a SQLite database relative
to MySQL and PostgreSQL. That said, you'll be stuck with limited
functionality. You won't be able to customize features or add a ton of
multi-user functionality.

MySQL/PostgreSQL
There are distinct differences between MySQL and PostgreSQL. That
said, given the context of the article, they fit into a similar category.

Both database types are great for enterprise solutions. If you need to
scale fast, MySQL and PostgreSQL are your best bet. They'll provide
long-term infrastructure and bolster your security.

Another reason they're great for enterprises is that they can handle
high performance activities. Longer insert, update, and select
statements need a lot of computing power. You'll be able to write
those statements with less latency than what a SQLite database
would give you.
SQLite, MySQL, and PostgreSQL all have their pros and cons. The
one you select should depend on your project or company's needs.
You should also consider what you need now versus several years
down the road.

The important thing to remember is that Python can integrate with


each database type.

How Python and SQL Databases Connect

Python and SQL databases connect through custom Python libraries.


You can import these libraries into your Python script.

Database-specific Python libraries serve as supplemental instructions.


These instructions guide your computer on how it can interact with
your SQL database. Otherwise, your Python code will be a foreign
language to the database you're trying to connect to.

Python SQLite3 tutorial (Database programming)


Ayesha TariqPublished: January 24, 2019Last updated: June 4, 2020

In this tutorial, we will work with the SQLite3 database programmatically


using Python.
SQLite in general is a server-less database that you can use within almost all
programming languages including Python. Server-less means there is no need
to install a separate server to work with SQLite so you can connect directly
with the database.
SQLite is a lightweight database that can provide a relational database
management system with zero-configuration because there is no need to
configure or set up anything to use it.
We will use SQLite version 3 or SQLite3, so let’s get started.

Table of Contents
 Create Connection
 SQLite3 Cursor
 Create Database
 Create Table
 Insert in Table
 Update Table
 Select statement
 Fetch all data
 SQLite3 rowcount
 List tables
 Check if a table exists or not
 Drop table
 SQLite3 exceptions
o DatabaseError
o IntegrityError
o ProgrammingError
o OperationalError
o NotSupportedError
 SQLite3 Executemany (Bulk insert)
 Close Connection
 SQLite3 datetime
Create Connection
To use SQLite3 in Python, first of all, you will have to import
the sqlite3 module and then create a connection object which will connect us
to the database and will let us execute the SQL statements.
You can a connection object using the connect() function:
import sqlite3

con = sqlite3.connect('mydatabase.db')
That will create a new file with the name ‘mydatabase.db’.

SQLite3 Cursor
To execute SQLite statements in Python, you need a cursor object. You can
create it using the cursor() method.
The SQLite3 cursor is a method of the connection object. To execute the
SQLite3 statements, you should establish a connection at first and then create
an object of the cursor using the connection object as follows:
con = sqlite3.connect('mydatabase.db')

cursorObj = con.cursor()

Now we can use the cursor object to call the execute() method to execute any
SQL queries.

Create Database
When you create a connection with SQLite, that will create a database file
automatically if it doesn’t already exist. This database file is created on disk;
we can also create a database in RAM by using :memory: with the connect
function. This database is called in-memory database.
Consider the code below in which we have created a database with
a try, except and finally blocks to handle any exceptions:
import sqlite3
from sqlite3 import Error

def sql_connection():

try:

con = sqlite3.connect(':memory:')

print("Connection is established: Database is created in memory")

except Error:

print(Error)

finally:

con.close()

sql_connection()

First, we import the sqlite3 module, then we define a function


sql_connection. Inside this function, we have a try block where
the connect() function is returning a connection object after establishing the
connection.
Then we have except block, which in case of any exceptions prints the error
message. If there are no errors, the connection will be established and will
display a message as follows.

After that, we have closed our connection in the finally block. Closing a
connection is optional, but it is a good programming practice, so you free the
memory from any unused resources.
Create Table
To create a table in SQLite3, you can use the Create Table query in
the execute() method. Consider the following steps:
1. Create a connection object.
2. From the connection object, create a cursor object.
3. Using the cursor object, call the execute method with create table
query as the parameter.
Let’s create employees with the following attributes:
employees (id, name, salary, department, position, hireDate)

The code will be like this:


import sqlite3

from sqlite3 import Error

def sql_connection():
try:

con = sqlite3.connect('mydatabase.db')

return con

except Error:

print(Error)

def sql_table(con):

cursorObj = con.cursor()

cursorObj.execute("CREATE TABLE employees(id integer PRIMARY KEY, name text, salary real,
department text, position text, hireDate text)")

con.commit()

con = sql_connection()

sql_table(con)
In the above code, we have defined two methods, the first one establishes a
connection and the second method creates a cursor object to execute the
create table statement.
The commit() method saves all the changes we make. In the end, both
methods are called.
To check if our table is created, you can use the DB browser for SQLite to
view your table. Open your mydatabase.db file with the program, and you
should see your table:

Insert in Table
To insert data in a table, we use the INSERT INTO statement. Consider the
following line of code:
cursorObj.execute("INSERT INTO employees VALUES(1, 'John', 700, 'HR', 'Manager', '2017-01-04')")

con.commit()

To check if the data is inserted, click on Browse Data in the DB Browser:


We can also pass values/arguments to an INSERT statement in
the execute() method. You can use the question mark (?) as a placeholder for
each value. The syntax of the INSERT will be like the following:
cursorObj.execute('''INSERT INTO employees(id, name, salary, department, position, hireDate)
VALUES(?, ?, ?, ?, ?, ?)''', entities)

Where entities contain the values for the placeholders as follows:


entities = (2, 'Andrew', 800, 'IT', 'Tech', '2018-02-06')

The entire code is as follows:


import sqlite3

con = sqlite3.connect('mydatabase.db')

def sql_insert(con, entities):

cursorObj = con.cursor()

cursorObj.execute('INSERT INTO employees(id, name, salary, department, position, hireDate)


VALUES(?, ?, ?, ?, ?, ?)', entities)
con.commit()

entities = (2, 'Andrew', 800, 'IT', 'Tech', '2018-02-06')

sql_insert(con, entities)

Update Table
To update the table, simply create a connection, then create a cursor object
using the connection and finally use the UPDATE statement in
the execute() method.
Suppose that we want to update the name of the employee whose id equals 2.
For updating, we will use the UPDATE statement and for the employee
whose id equals 2. We will use the WHERE clause as a condition to select
this employee.
Consider the following code:
import sqlite3

con = sqlite3.connect('mydatabase.db')

def sql_update(con):
cursorObj = con.cursor()

cursorObj.execute('UPDATE employees SET name = "Rogers" where id = 2')

con.commit()

sql_update(con)

This will change the name from Andrew to Rogers as follows:

Select statement
You can use the select statement to select data from a particular table. If you
want to select all the columns of the data from a table, you can use the
asterisk (*). The syntax for this will be as follows:
select * from table_name

In SQLite3, the SELECT statement is executed in the execute method of the


cursor object. For example, select all the columns of the employees’ table,
run the following code:
cursorObj.execute('SELECT * FROM employees ')
If you want to select a few columns from a table, then specify the columns
like the following:
select column1, column2 from tables_name

For example,
cursorObj.execute('SELECT id, name FROM employees')

The select statement selects the required data from the database table, and if
you want to fetch the selected data, the fetchall() method of the cursor object
is used. We will demonstrate this in the next section.

Fetch all data


To fetch the data from a database, we will execute the SELECT statement
and then will use the fetchall() method of the cursor object to store the values
into a variable. After that, we will loop through the variable and print all
values.
The code will be like this:
import sqlite3

con = sqlite3.connect('mydatabase.db')

def sql_fetch(con):

cursorObj = con.cursor()

cursorObj.execute('SELECT * FROM employees')

rows = cursorObj.fetchall()

for row in rows:


print(row)

sql_fetch(con)

The above code will print out the records in our database as follows:

You can also use the fetchall() in one line as follows:


[print(row) for row in cursorObj.fetchall()]

If you want to fetch specific data from the database, you can use the WHERE
clause. For example, we want to fetch the ids and names of those employees
whose salary is greater than 800. For this, let’s populate our table with more
rows, then execute our query.
You can use the insert statement to populate the data, or you can enter them
manually in the DB browser program.
Now, to fetch id and names of those who have a salary greater than 800:
import sqlite3

con = sqlite3.connect('mydatabase.db')

def sql_fetch(con):

cursorObj = con.cursor()

cursorObj.execute('SELECT id, name FROM employees WHERE salary > 800.0')

rows = cursorObj.fetchall()
for row in rows:

print(row)

sql_fetch(con)

In the above SELECT statement, instead of using the asterisk (*), we


specified the id and name attributes. The result will be like the following:

SQLite3 rowcount
The SQLite3 rowcount is used to return the number of rows that are affected
or selected by the latest executed SQL query.
When we use rowcount with the SELECT statement, -1 will be returned as
how many rows are selected is unknown until they are all fetched. Consider
the example below:
print(cursorObj.execute('SELECT * FROM employees').rowcount)
Therefore, to get the row count, you need to fetch all the data, and then get
the length of the result:
rows = cursorObj.fetchall()

print len (rows)

When you use the DELETE statement without any condition (a where
clause), that will delete all the rows in the table, and it will return the total
number of deleted rows in rowcount.
print(cursorObj.execute('DELETE FROM employees').rowcount)

If no row is deleted, it will return zero.


List tables
To list all tables in an SQLite3 database, you should query the sqlite_master
table and then use the fetchall() to fetch the results from the SELECT
statement.
The sqlite_master is the master table in SQLite3, which stores all tables.
import sqlite3

con = sqlite3.connect('mydatabase.db')

def sql_fetch(con):

cursorObj = con.cursor()

cursorObj.execute('SELECT name from sqlite_master where type= "table"')

print(cursorObj.fetchall())

sql_fetch(con)

This will list all the tables as follows:


Check if a table exists or not
When creating a table, we should make sure that the table is not already
existed. Similarly, when removing/ deleting a table, the table should exist.
To check if the table doesn’t already exist, we use “if not exists” with the
CREATE TABLE statement as follows:
create table if not exists table_name (column1, column2, …, columnN)

For example:
import sqlite3

con = sqlite3.connect('mydatabase.db')

def sql_fetch(con):

cursorObj = con.cursor()
cursorObj.execute('create table if not exists projects(id integer, name text)')

con.commit()

sql_fetch(con)

Similarly, to check if the table exists when deleting, we use “if exists” with
the DROP TABLE statement as follows:
drop table if exists table_name

For example,
cursorObj.execute('drop table if exists projects')
We can also check if the table we want to access exists or not by executing
the following query:
cursorObj.execute('SELECT name from sqlite_master WHERE type = "table" AND name = "employees"')

print(cursorObj.fetchall())

If the employees’ table exists, it will return its name as follows:


If the table name we specified doesn’t exist, an empty array will be returned:
Drop table
You can drop/delete a table using the DROP statement. The syntax of the
DROP statement is as follows:
drop table table_name

To drop a table, the table should exist in the database. Therefore, it is


recommended to use “if exists” with the drop statement as follows:
drop table if exists table_name

For example,
import sqlite3

con = sqlite3.connect('mydatabase.db')

def sql_fetch(con):

cursorObj = con.cursor()

cursorObj.execute('DROP table if exists employees')

con.commit()

sql_fetch(con)
SQLite3 exceptions
Exceptions are the run time errors. In Python programming, all exceptions
are the instances of the class derived from the BaseException.
In SQLite3, we have the following main Python exceptions:
DatabaseError
Any error related to the database raises the DatabaseError.
IntegrityError
IntegrityError is a subclass of DatabaseError and is raised when there is a
data integrity issue. For example, foreign data isn’t updated in all tables
resulting in the inconsistency of the data.
ProgrammingError
The exception ProgrammingError raises when there are syntax errors or table
is not found or function is called with the wrong number of parameters/
arguments.
OperationalError
This exception is raised when the database operations are failed, for example,
unusual disconnection. This is not the fault of the programmers.
NotSupportedError
When you use some methods that aren’t defined or supported by the
database, that will raise the NotSupportedError exception.
SQLite3 Executemany (Bulk insert)
You can use the executemany statement to insert multiple rows at once.
Consider the following code:
import sqlite3

con = sqlite3.connect('mydatabase.db')

cursorObj = con.cursor()

cursorObj.execute('create table if not exists projects(id integer, name text)')

data = [(1, "Ridesharing"), (2, "Water Purifying"), (3, "Forensics"), (4, "Botany")]

cursorObj.executemany("INSERT INTO projects VALUES(?, ?)", data)

con.commit()

Here we created a table with two columns, and “data” has four values for
each column. We pass the variable to the executemany() method along with
the query.
Note that we have used the placeholder to pass the values.
The above code will generate the following result:
Close Connection
Once you are done with your database, it is a good practice to close the
connection. You can close the connection by using the close() method.
To close a connection, use the connection object and call the close() method
as follows:
con = sqlite3.connect('mydatabase.db')

#program statements

con.close()

SQLite3 datetime
In the Python SQLite3 database, we can easily store date or time by
importing the datatime module. The following formats are the most common
formats you can use for datetime:
YYYY-MM-DD

YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS

YYYY-MM-DD HH:MM:SS.SSS

HH:MM

HH:MM:SS

HH:MM:SS.SSS

now

Consider the following code:


import sqlite3

import datetime

con = sqlite3.connect('mydatabase.db')

cursorObj = con.cursor()

cursorObj.execute('create table if not exists assignments(id integer, name text, date date)')
data = [(1, "Ridesharing", datetime.date(2017, 1, 2)), (2, "Water Purifying", datetime.date(2018, 3, 4))]

cursorObj.executemany("INSERT INTO assignments VALUES(?, ?, ?)", data)

con.commit()

In this code, we imported the datetime module first, and we have created a
table named assignments with three columns.
The data type of the third column is a date. To insert the date in the column,
we have used datetime.date. Similarly, we can use datetime.time to handle
time.
The above code will generate the following output:

The great flexibility and mobility of the SQLite3 database make it the first
choice for any developer to use it and ship it with any product he works with.
You can use SQLite3 databases in Windows, Linux, Mac OS, Android, and
iOS projects due to their awesome portability. So you ship one file with your
project and that’s it.

You might also like