0% found this document useful (0 votes)
6 views102 pages

Scs 1619

The document provides an overview of GUI programming in Python using the Tkinter module, detailing its various widgets, layout managers, and how to manage fonts and colors. It explains the three layout managers: Pack, Grid, and Place, along with examples of their usage. Additionally, it covers the creation and customization of different widgets such as Labels and Entry fields.

Uploaded by

sowndharyak1988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views102 pages

Scs 1619

The document provides an overview of GUI programming in Python using the Tkinter module, detailing its various widgets, layout managers, and how to manage fonts and colors. It explains the three layout managers: Pack, Grid, and Place, along with examples of their usage. Additionally, it covers the creation and customization of different widgets such as Labels and Entry fields.

Uploaded by

sowndharyak1988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 102

GUI PROGRAMMING WITH PYTHON

In python text only programs can be created using Command line


Interface. Graphical user interface(GUI) can be created using tkinter module
in python.

3.1 INTRODUCTION TO GUI LIBRARY IN PYTHON

Tkinter is a module in the Python standard library which serves as an


interface to Tk (ie) simple toolkit. There are many other toolkits also available
to create GUI.

Tkinter provides the following widgets:

 button
 canvas
 checkbutton
 combobox
 entry
 frame
 label

1
 listbox
 menu
 message
 progressbar
 radiobutton
 scrollbar
 spinbox
 text

Tkinter also provides three layout managers:

 place - It positions widgets at absolute locations


 grid - It arranges widgets in a grid
 pack - It packs widgets into a cavity

3.2 LAYOUT MANAGEMENT

The Layout Managers are used to arrange components in a particular


manner. It is used to organize the conponents. There are three Layout
Management in python:

1. Pack Layout
2. Grid Layout
3. Place Layout

3.2.1 Pack Layout Manager

2
It is a simple layout manager. Here widgets can be organized in
horizontal and vertical boxes. It is used to place each widget next to previous
widget. It will be called without any arguments and it will position and size
the widgets in a reasonable way. Whenever the user wants to have a series of
widgets in a vertical or horizontal row, the pack layout manager is fairly
simple to use. The layout is controlled with the fill, expand, and side options.

Example:

fromtkinter import * top=Tk()


l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True)
l2.pack(fill=X,side=RIGHT)
top.mainloop()

Output:

Explanation: Label l1 has been placed in top position, it is filled in X axis. Label
l2 has been placed in Right Position and it is also filled in X axis. Since
expand attribute has the value True for Label l1,it can be stretched.

3
Padding Option in Pack Layout:
The pack() manager has four padding options:
1. Internal Padding
2. External padding
3. Padding in X Direction.
4. Padding in Y Direction.
External Padding in Horizontal direction(padx)
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True,padx=10)
l2.pack(fill=X,side=TOP,padx=10)
top.mainloop()

Output:

4
External Padding in Vertical direction (pady)

Example:

fromtkinter import *

top=Tk()

l1=Label(top,text="Label1",bg="blue")

l2=Label(top,text="Label2",bg="red" )

l1.pack(fill=X,side=TOP,expand=True,pady=10)

l2.pack(fill=X,side=TOP,pady=10)

top.mainloop()

Output:

5
Internal Padding in Horizontal direction(ipadx)

Example:

fromtkinter import *

top=Tk()

l1=Label(top,text="Label1",bg="blue")

l2=Label(top,text="Label2",bg="red" )

l1.pack(fill=X,side=TOP,expand=True,ipadx=10)

l2.pack(fill=X,side=TOP,ipadx=10)

top.mainloop()

Output:

Internal Padding in Y Direction(ipady):

Example:

fromtkinter import *

6
top=Tk()

l1=Label(top,text="Label1",bg="blue")

l2=Label(top,text="Label2",bg="red" )

l1.pack(fill=X,side=TOP,expand=True,ipadx=10)

l2.pack(fill=X,side=TOP,ipady=10)

top.mainloop()

Output:

3.2.2. Place Layout


Place is the most complex manager out of the 3 managers. It uses
absolute positioning, when we choose place lay out in our design, then we
need to specify the position of the widgets using x and y coordinates. The size
and position of the widgets will not be changed when we resize the window.
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")

7
l2=Label(top,text="Label2",bg="red" )
l1.place(x=10,y=50)
l2.place(x=10,y=100)
top.mainloop()
Output:

Explanation:

Here Label1 is placed in the position (10,50) and label2 is placed in


the position (10,100).

3.2.3 Grid Layout

Pack Layout is not easy to understand and it is difficult to change the


existing design. By using place layout, we can control the positioning of

8
widgets but it is complex than pack. Grid is one of the most versatile layout
manager out of the three layout managers in python. By using Grid layout, the
widgets can be placed in rows and columns.

Example:

fromtkinter import *

top=Tk()

l1=Label(top,text="Label1",bg="blue")

l2=Label(top,text="Label2",bg="red" )

l3=Label(top,text="Label2",bg="green" )

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

l2.grid(row=0,column=1)

l3.grid(row=1,column=1)

top.mainloop()

Output:

9
Explanation:

Here Label 1 is placed in 0th row and 0th column. Label 2 is placed in 0th row
and 1st column and Label 3 is placed in 1st row and 1st column.

3.3 FONT

There are three ways to specify font in python.

1. By using Font Tuple

2. By using Font Object

3. By using XFont

3.3.1 Simple Font Tuple

10
Font can be specified using tuple.Herethe font tuple consists of
threeelements.First element specifies font family ,second element specifies
font size and third element specifies font style.

Ex: t =(“Arial”,14,”Bold”)

Example:

fromtkinter import * top=Tk()

b1=Button(text="submit",font=("Arial","16","bold"))

b1.pack()

top.mainloop()

Output:

Explanation:

Text for the Button has been set in the Arial font with size 16 and Bold style.

3.3.2 Font Object

Font object can be created by importing tkFont module.

11
Syntax for Font class constructor is:

Import tkFont

Font f1=tkFont.Font(parameters,…..)

Here is the list of parameters:

Family − The font family name as a string.

size − The font height as an integer in points. To get a font n


pixels high, use -n.

weight − "bold" for boldface, "normal" for regular

weight. Slant − "italic" for italic, "roman" for unslanted.

underline − 1 for underlined text, 0 for normal.

Overstrike − 1 for overstruck text, 0 for normal

Example:

fromtkinter import *

fromtkFont import *

top=Tk()

12
f1=Font(family="Helvetica",size=20,weight="bold",slant="italic",underline=1
,overstrike=1)

l1=Label(top,text="Label1",bg="blue",font=f1)

l1.pack()

top.mainloop()

X Window Fonts:

If you are running under the X Window System, you can use any of the X font
names.

3.4 COLORS

Tkinter represents colors with strings. There are two general ways to specify
colors in Tkinter :

 We can use a string specifying the proportion of red, green and blue in
hexadecimal digits. For example,

 "#fff" -- white,
 "#000000" -- black,
 "#000fff000" -- pure green
 "#00ffff" -- pure cyan
 We can also use any locally defined standard following color names.

 "white"

 "black"
13
 "red"

 "green"

 "blue"

 "cyan"

 "yellow"

 "magenta"

The common color options are :

Active background − Specifies Background color for the widget when the
widget is active.

activeforeground − Specifies Foreground color for the widget when the


widget is active.

background − Specifies Background color for the widget. This can


also be represented as bg.

disabledforeground − Specifies Foreground color for the widget when the


widget is disabled.

foreground − Specifies Foreground color for the widget. This can also
be represented as fg.
highlightbackground − Specifies Background color of the highlight region

14
when the widget has focus.

highlightcolor − Specifies Foreground color of the highlight region


when the widget has focus.

selectbackground − Specifies Background color for the selected items of


the widget.

selectforeground − Specifies Foreground color for the selected items of


the widget.

Example:

fromtkinter import *

top=Tk()

b1=Button(text="submit",bg="red",fg="white")

b1.pack()

top.mainloop()

Output:

Explanation:

15
Here the back ground of the button is red in color and foreground color of the
button is white in colour.

3.5 CANVAS

The Canvas is a rectangular area used for drawing pictures or other


complex layouts. Graphics, text, widgets or frames can be placed on a Canvas.

Syntax:
w = Canvas ( top, option=value, ... )
top – It represents the parent window.
Options − commonly used options for this widget. These options can be
used as key-value pairs separated by commas.
Commonly used Options are:
bd - Border Width of the canvas
bg - Background color of the canvas
cursor - Cursor used in the canvas like circle,arrow and dot.
relief - Type of the border
width - Width of the
canvas Items supported by canvas:

1. Arc

2. Image

3. Line

4. Oval
16
5. Polygon

ARC
Creates an arc item, which can be a chord or a simple arc.

Syntax:

create_arc(x0, y0, x1, y1, options…..)

x0,y0,x1,y1-Top Left and Bottom Right coordinates of Bounding Rectangle

Commonly used Options:

start,extend-Specifies which section to draw

Example:

fromtkinter import * root=Tk()

w = Canvas(root, width=500, height=500)

coord = 10, 50, 240, 210

arc = w.create_arc(coord, start=0, extent=150, fill="blue")

w.pack()

Output:

17
Explanation:

Here Arc is drawn with blue color and within the bounded rectangle with top
left(10,50)position and bottom right(240,210) position and started from angle
0 and extended till 150 degree.

3.5.1 Image

Creates an image , which can be an instance of either the BitmapImage or the


PhotoImage classes.

Syntax:

Create_image(x,y,options….)

x,y-Specifies the position of the image

commonly used options:

18
anchor=Where to place the image relative to the given position.
Default is CENTER.

image=image object

Example:

fromtkinter import *

root=Tk()

w = Canvas(root, width=500,

height=500) w.create_image("F:\

img2",50,50) w.pack()

root.mainloop()

3.5.2 Line

Creates a line item.

Syntax:

canvas.create_line(x0, y0, x1, y1, ...,xn, yn,

options) x0,y0,x1,y1->coordinates of line

Commonly used options:

activefill-Color of the line when it is

active width -Width of the line

19
Example:

fromtkinter import *

root=Tk()

w = Canvas(root, width=500, height=500)

w.create_line(10,10,100,100,activefill="red")

w.pack()

root.mainloop()

Output:

3.5.3 Oval

20
Creates a circle or an ellipse at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right corners of the bounding rectangle for
the oval.

Syntax:

canvas.create_oval(x0, y0, x1, y1, options)

x0, y0, x1, y1- the top left and bottom right corners of the bounding
rectangle

Options:

activefill-Color of the oval when it is active

width -Width of the line

Example:

fromtkinter import * root=Tk()

w = Canvas(root, width=500, height=500)

w.create_oval(10,10,100,100,activefill="red")

w.pack()

root.mainloop()

21
Output:

3.5.4 Polygon

Creates a polygon item that must have at least three vertices.

Syntax:

canvas.create_polygon(x0, y0, x1, y1,...xn, yn,

options) x0, y0, x1, y1,...xn, yn-Coordinates of

polygon Options:

Activefill-Color of the oval when it is

active width -Width of the line

Example

fromtkinter import *

22
root=Tk()

w = Canvas(root, width=500, height=500)

w.create_polygon(50,50,20,20,100,100,activefill="red")

w.pack()

root.mainloop()

3.6 WIDGETS IN PYTHON

Widgets are standard graphical user interface (GUI) elements, like different
kinds of buttons and menus.

3.6.1 Label

A Label widget shows text to the user about other widgets used in the
application. The widget can be updated programmatically.

Syntax to create Label:

w=Label (root

,options) root - Parent

Window

23
List of commonly used options are given below:

Table 3.1: Options for Label Widget

Option Description
anchor It specifies the exact position of the text within the size provided to
the widget. The default value is CENTER, which is used to center
the text within the specified space.
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor. eg: dot, arrow, circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
underline Underline the label text

24
Example:

fromtkinter import *

root=Tk()

l1=Label(root,text="Enter User Name",bg="green",fg="white")

l1.pack()

root,mainloop()

Output:

Explanation:

Here Label has been created with green background color and white
foreground color with the text “Enter User Name”.

25
ENTRY

The Entry widget is used to create the single line text-box to the user to
accept a value from the user. It can accept the text strings from the user. It can
receive one line of text from the user. For multiple lines of text, the text
widget will be used.

Syntax for creating Entry

Widget: w=Entry(root,

options)

root-Main Window

Table 3.2: List of commonly used options for Entry Widget

Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
26
pady Vertical padding of text
Option Description
relief Specifies type of border
text Text to be displayed in the widget
undeline Underline the label text
selectbackground Background color of the selected text
selectforeground Foreground color of the selected text
show Specifies the character used to mask characters in the
text box

Example:

fromtkinter import *

root=Tk()

l1=Label(root,text="Enter User Name",bg="green",fg="white")

e1=Entry(root,show="*")

l1.pack(side=LEFT)

e1.pack(side=RIGHT)

root.mainloop()

27
Output:

28
Explanation:

Here Label and entry widgets are created.Since the show attribute value is
*,the characters entered in the text box appeared as “*”.

3.6.2 Button

Button Widget is used to create various kinds of buttons.The user can interact
with the button.They can contain text or images.

Syntax for creating Button:

b=Button(root,options)

root-main window

29
Table 3.3: List of commonly used options for Button

Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
underline Underline the label text
command It is set to function name which will be called the button is
clicked

Example:
fromtkinter import *
root=Tk()

30
b1=Button(root,text="Submit",bg="blue",fg="white")
b1.pack()
root.mainloop()
Output:

3.6.3 Checkbutton

The Checkbutton is used to track the user's choices provided to the


application. Checkbutton is used to implement the on/off
selections.TheCheckbutton can contain the or images or text. The
Checkbutton is mostly used to provide many choices to the user among which,
the user needs to choose the one.

Syntax for creating Check Button:

b=CheckButton(root,options)

root-main window

31
Table 3.4: List of possible options for Checkbutton

Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
undeline Underline the label text
command It is set to function name whicjh will be called the button is
clicked
offvalue Set value to the control variable if the button is
checked.Default Value is 1
onvalue Set value to the control variable if the button is
unchecked.Default Value is 0
selectcolor Set color of the check button when it is checked.
selectimage Set the image to be shown when it is checked.

Example:

fromtkinter import *

32
root=Tk()

c1 = Checkbutton(root, text = "C", onvalue = 1, offvalue = 0, height = 2,


width = 10)

c2 = Checkbutton(root, text = "C++", onvalue = 1, offvalue = 0, height = 2,


width = 10)

c3 = Checkbutton(root, text = "JAVA", onvalue = 1, offvalue = 0, height = 2,


width = 10)

c1.pack()

c2.pack()

c3.pack()

root.mainloop()

Output:

33
3.6.4 Radiobutton

The Radiobutton widget is used to implement one-of-many selection. It shows


multiple options to the user out of which, the user can select only one option.
It is possible to display the multiple line text or images on the radiobuttons.
To keep track the user's selection ,theradiobutton is associated with a single
variable.EachRadio button displays a single value for that particular variable.

Syntax for creating Radio Button:

b=RadioButton(root,options)

root-main window

34
Table 3.5: List of possible options for Radiobutton

Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
underline Underline the label text
command It is set to function name whicjh will be called the button
is clicked
value Set value to the control variable if the button is selected.
selectcolor Set color of the check button when it is checked.
selectimage Set the image to be shown when it is checked.
variable It is used to keep track of user choices.

34
Example:

fromtkinter import *

root=Tk()

r1 = Radiobutton(root, text = "C", value = 1, height = 2, width = 10)

r2 = Radiobutton(root, text = "C++", value = 2, height = 2, width =

10)

r3 = Radiobutton(root, text = "JAVA",value = 3, height = 2, width = 10)

r1.pack()

r2.pack()

r3.pack()

root.mainloop()

Output:

35
36
3.6.5 Listbox

The Listbox widget is used to display the list items to the user.The user can
choose one or more items from the list depending upon the configuration.

Syntax for

creatingListBox:

b=Listbox(root,options)

root-main window

Table 3.6: List of possible options foe Listbox

Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text

37
pady Vertical padding of text
relief Specifies type of border
value Set value to the control variable if the button is selected.
selectbackground Set back ground color of the selected text.
xscrollcommand User can scroll the list box horizontally
yscrollcommand User can scroll the list box vertically

Example:

fromtkinter import *

top = Tk()

lbl = Label(top,text = "A list of favourite countries...")

listbox = Listbox(top)

listbox.insert(1,"India")

listbox.insert(2, "USA")

listbox.insert(3, "Japan")

listbox.insert(4, "Austrelia")

lbl.pack()

listbox.pack()

38
top.mainloop()

39
Output:

3.6.6 Message

Its functionality is very similar to Label widget, except that it can


automatically wrap the text, maintaining a given width.

Syntax for creating

Message:

m=Message(root,options)

root-main window

Table 3.7: List of possible options for Message

Option Description

bg Specifies background color of the widget

bd Specifies border width. Default is 2 pixels


40
cursor Specifies type of cursor.eg:dot,arrow,circle

Option Description

font Specifies font type of the text written inside the widget

fg Foreground color of the widget

height Height of the widget

width Width of the widget

image Specifies image to be displayed in the widget

padx Horizontal padding of text

pady Vertical padding of text

relief Specifies type of border

Example:

fromtkinter import *

top = Tk()

msg = Message( top, text = "Welcome to Javatpoint")

msg.pack()

top.mainloop()

Output:
41
42
3.6.7 Text

Tkinter provides us the Entry widget which is used to implement the single
line text box. Text widget provides advanced capabilities that allow us to edit
a multiline text and format the way it has to be displayed, such as changing its
color and font. We can also use the structures like tabs and marks to locate
specific sections of the text, and apply changes to those areas.

Syntax for creating

Message:

T=Text(root,options)

root-main window

Table 3.8: List of possible options for Text

Option Description

43
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
xscrollcommand User can scroll the text widget horizontally
yscrollcommand User can scroll the text widget vertically
selectbackground Background color of the selected text

Table 3.9: General Methods

Description
Method
delete(startindex, This method is used to delete the characters of the
endindex) specified range
get(startindex,endindex) It returns the characters present in the specified
range.

44
insert(index, string) It is used to insert the specified string at the given

index.

Mark Handling Methods:

Marks are used to bookmark the specified position between the characters of
the associated text.

Table 3.10: List of Mark handling methods

Method Description
mark_set(mark,index) It is used to create mark at the specified index.
mark_unset(mark) It is used to clear the given mark
mark_names() It is used to return names of all the marks

Tag Handling Methods:

The tags are the names given to the specific areas of the text. The tags are
used to configure the different areas of the text separately.

Table 3.11: The list of tag-handling methods

Method Description
tag_add(tagname, startindex, It is used to tag the characters in the
endindex) given range

45
tag_config() It is used to configure the tag properties

tag_delete(tagname) It is used to delete the given tag


tag_remove(tagname, startindex, It is used to remove the tag from the
endindex) specified range

Example:

fromtkinter import *

top = Tk()

text = Text(top)

text.insert(INSERT, "Name....")

text.insert(END, "Salary.....")

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", background="black", foreground="white")

Output:

46
Explanation:

The tag “Write Here” tags the characters from the index 0 to 4.The tag “Click
Here” tags the characters from the index 8 to 13.These tags are configured
using the method tag_config().

3.6.8 Spinbox

The Spinbox widget is a variant of the standard Tkinter Entry widget, which
can be used to select from a fixed number of values.

Syntax:

w = Spinbox( master, option, ... )

Parameters

 master − This represents the parent window.


 options − Here is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated by
commas.
47
 The Spinbox control is an alternative to the Entry control. It
provides the range of values to the user, out of which, the user can
select only one value.It is used in the case where a user is given
some fixed number of values to choose from.
 Syntax for creating Message:
 S=Spinbox(root,options)
 root-main window

Table 3.12: List of options for Spinbox

Sr.No. Option & Description

1
activebackground
The color of the slider and arrowheads when the mouse is over them.

2
bg
The color of the slider and arrowheads when the mouse is not over them.

3
bd
The width of the 3-d borders around the entire perimeter of the trough,
and also the width of the 3-d effects on the arrowheads and slider.
Default is no border around the trough, and a 2-pixel border around
the arrowheads and slider.

48
4
command
A procedure to be called whenever the scrollbar is moved.

5
cursor
The cursor that appears when the mouse is over the scrollbar.

6
disabledbackground
The background color to use when the widget is disabled.

7
disabledforeground
The text color to use when the widget is disabled.

8
fg
Text color.

9
font
The font to use in this widget.

10
format
Format string. No default value.

49
11
from_
The minimum value. Used together with to to limit the spinbox
range.

12
justify
Default is LEFT

13
relief
Default is SUNKEN.

14
repeatdelay
Together with repeatinterval, this option controls button auto-
repeat. Both values are given in milliseconds.

15
repeatinterval
See repeatdelay.

16
state
One of NORMAL, DISABLED, or "readonly". Default is
NORMAL.

17
textvariable

50
No default value.

18
to
See from.

19
validate
Validation mode. Default is NONE.

20
validatecommand
Validation callback. No default value.

21
values
A tuple containing valid values for this widget. Overrides
from/to/increment.

22
vcmd
Same as validatecommand.

23
width
Widget width, in character units. Default is 20.

51
24
wrap
If true, the up and down buttons will wrap around.

25
xscrollcommand
Used to connect a spinbox field to a horizontal scrollbar. This
option should be set to the set method of the corresponding
scrollbar.

Methods

Table 3.13: Methods of Spinbox objects

Sr.No. Methods & Description

1
delete(startindex [,endindex])
This method deletes a specific character or a range of text.

2
get(startindex [,endindex])
This method returns a specific character or a range of text.

3
identify(x, y)

52
Identifies the widget element at the given location.

4
index(index)
Returns the absolute value of an index based on the given index.

5
insert(index [,string]...)
This method inserts strings at the specified index location.

6
invoke(element)
Invokes a spinbox button.

Example

Try the following example yourself −


from Tkinter import *

master = Tk()

53
w = Spinbox(master, from_=0, to=10)
w.pack()

mainloop()

When the above code is executed, it produces the following result −

Example:

fromtkinter import *

top = Tk()

spin = Spinbox(top, from_= 0, to = 25)

spin.pack()

top.mainloop()

Output:

54
3.7 FRAME

Frame widget is used to organize 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 organize the widgets to the python application.

Syntax for creating Frame:

S=Frame(root,options)

root-main window

Table 3.14: List of possible options for Frame

Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels

55
cursor Specifies type of cursor.eg:dot,arrow,circle
height Height of the widget
width Width of the widget
Relief Specifies type of border

Example:

fromtkinter import *
top = Tk()
Topframe = Frame(top)
Topframe.pack(side = TOP)
Bottomframe = Frame(top)
Bottomframe.pack(side =BOTTOM)
btn1 = Button(Topframe, text="Submit", fg="red",activebackground = "red")
btn1.pack(side = LEFT)
btn2 = Button(Topframe, text="Remove", fg="brown", activebackground =
"brown")
btn2.pack(side = RIGHT)
btn3 = Button(Bottomframe, text="Add", fg="blue", activebackground =
"blue")
btn3.pack(side = LEFT)

56
btn4 = Button(Bottomframe, text="Modify", fg="black", activebackground =
"white")
btn4.pack(side = RIGHT)
top.mainloop()

Output:

Explanation:

Here two frames (Top Frame and Bottom Frame) have been
created.Topframe contains submit and remove buttons and Bottom frame
contains Add and modify buttons .

3.8 EVENTS AND BINDINGS IN PYTHON

Binding function is used to deal with the events. We can bind Python’s
Functions and methods to an event as well as we can bind these functions to
any particular widget. Events can come from various sources, including key
presses and mouse operations by the user. Tkinter provides a powerful

57
mechanism to let you deal with events yourself. For each widget, you
can bind Python functions and methods to events.

widget.bind(event, handler)

If an event matching the event description occurs in the widget, the


given handler is called with an object describing the event.

A Tkinter application spends most of its time inside an event loop (entered via
the mainloop method). Events can come from various sources, including key
presses and mouse operations by the user, and redraw events from the window
manager.
Tkinter provides a powerful mechanism to deal with events. For each
widget, you can bind Python functions and methods to events.
widget.bind(event, handler)
If an event matching the event description occurs in the widget, the
given handler is called with an object describing the event.
Here’s a simple example:
Example Program1:Capturing clicks in a window
from tkinter import *
window = Tk()
def callback(event):
print ("clicked at", event.x, event.y)
frame = Frame(window, width=100, height=100)
frame.bind("<Button-1>", callback)
frame.pack()
window.mainloop()

58
In this example, the bind method of the frame widget is used to bind a
callback function to an event called <Button-1>. Run this program and click
in the window that appears. Each time you click, a message like “clicked at
44 63” is printed to the console window.
Keyboard events are sent to the widget that currently owns the
keyboard focus. The focus_set method can be used to move focus to a
widget:
Example Program2:Capturing keyboard events
from tkinter import *
window = Tk()
def key(event):
print("pressed", repr(event.char))
def callback(event):
frame.focus_set()
print("clicked at", event.x, event.y)
frame = Frame(window, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()
window.mainloop()

If you run this script, you’ll find that you have to click in the frame before it
starts receiving any keyboard events.
Some of the commonly used events and some event properties are listed
below:

59
Table 3.15: Events

Event Description
<Bi-Motion> An event occurs when a mouse button is moved while
being held down on the widget.
<Button-i> Button-1, Button-2, and Button-3 identify the left,
middle, and right buttons. When a mouse buttonis
pressed over the widget, Tkinter automatically grabs
the mouse pointer’s location. ButtonPressed-
iissynonymous with Button-i.
<ButtonReleased- An event occurs when a mouse button is released.
i>
<Double-Button-i> An event occurs when a mouse button is double-
clicked.
<Enter> An event occurs when a mouse pointer enters the
widget.
<Key> An event occurs when a key is pressed.
<Leave> An event occurs when a mouse pointer leaves the
widget.
<Return> An event occurs when the Enter key is pressed. You
can bind any key such as A, B, Up, Down, Left, Right
in the keyboard with an event.
<Shift+A> An event occurs when the Shift+Akeys are pressed.
You can combine Alt, Shift, and Control with other
keys.
<Triple-Button-i> An event occurs when a mouse button is triple-clicked.

60
Table 3.16: Event Properties

Event Property Description


char The character entered from the keyboard for key events.
keycode The key code (i.e., Unicode) for the key entered from
the keyboard for key events.
keysym The key symbol (i.e., character) for the key entered
from the keyboard for key events.
num The button number (1, 2, 3) indicates which mouse
button was clicked.
widget The widget object that fires this event.
x and y The current mouse location in the widget in pixels.
x_ _root and The current mouse position relative to the upper-left
y_root corner of the screen, in pixels.

The program MouseKeyEventDemo processes mouse and key events. It


displays the window asshown in Figure 1a. The mouse and key events are
processed and the processing informationis displayed in the command
window, as shown in Figure 1 b.

61
Example Program3 : MouseKeyEventDemo
from tkinter import * # Import all definitions from tkinter
class MouseKeyEventDemo:
def init (self):
window = Tk() # Create a window
window.title("Event Demo") # Set a title
canvas = Canvas(window, bg = "white", width = 200, height = 100)
canvas.pack()
# Bind with <Button-1> event
canvas.bind("<Button-1>",
self.processMouseEvent)
# Bind with <Key> event
canvas.bind("<Key>", self.processKeyEvent)
canvas.focus_set()
window.mainloop() # Create an event loop
def processMouseEvent(self, event):
print("clicked at", event.x, event.y)
print("Position in the screen", event.x_root, event.y_root)
print("Which button is clicked? ", event.num)
def processKeyEvent(self, event):
print("keysym? ", event.keysym)
print("char? ", event.char)
print("keycode? ", event.keycode)
MouseKeyEventDemo() # Create GUI

62
Figure 1 a Output Window of Program3

Figure 1 bOutput of Program3 for mouseclick and keypress

The program creates a canvas and binds a mouse event <Button-1>with the
callbackfunction processMouseEventon the canvas. Nothing is drawn on the
canvas.So it is blank as shown in Figure 1a. When the left mouse button is
clicked on the canvas,an event is created. The processMouseEventis invoked
to process an event that displaysthe mouse pointer’s location on the canvas, on

63
the screen, and which mousebutton is clicked.The Canvas widget is also the
source for the key event. The program binds a key eventwith the callback
function processKeyEventon the canvas and sets the focus onthe canvas so
that the canvas will receive input from the keyboard.
The example Program EnlargeShrinkCircledisplays a circle on the canvas.
The circle radius is increased with a left mouseclick and decreased with a
right mouse click, as shown in Figure 2 a,2 b, 2c.

64
Example Program4 : EnlargeShrinkCircle
from tkinter import * # Import all definitions from tkinter
class EnlargeShrinkCircle:
def init (self):
self.radius = 50
window = Tk() # Create a window
window.title("Control Circle Demo") # Set a title
self.canvas = Canvas(window, bg = "white",width = 200, height = 200)
self.canvas.pack()
self.canvas.create_oval(100 - self.radius, 100 - self.radius,100 + self.radius,
100 + self.radius, tags = "oval")
# Bind canvas with mouse events
self.canvas.bind("<Button-1>", self.increaseCircle)
self.canvas.bind("<Button-3>", self.decreaseCircle)
window.mainloop() # Create an event loop
def increaseCircle(self, event):
self.canvas.delete("oval")
if self.radius< 100:
self.radius += 2
self.canvas.create_oval(100 - self.radius, 100 - self.radius,100 + self.radius,
100 + self.radius, tags = "oval")
def decreaseCircle(self, event):
self.canvas.delete("oval")
if self.radius> 2:
self.radius -= 2
self.canvas.create_oval(100 - self.radius, 100 - self.radius,100 + self.radius,
100 + self.radius, tags = "oval")
EnlargeShrinkCircle() # Create GUI

65
Figure 2 a Output Window of Program4

Figure 2 b Circle Radius Enlarged using Left Mouse


of Program4

66
Figure 2 c Circle Radius Shrinked using Right Mou
of Program4

The program creates a canvas and displays a circle on the canvas with an
initialradius of 50. The canvas is bound to a mouse event <Button-1>with
thehandler increaseCircleand to a mouse event <Button-3>with the
handlerdecreaseCircle. When the left mouse button is pressed, the
increaseCirclefunction is invoked to increase the radius and redisplay the
circle.When the right mouse button is pressed, the decreaseCirclefunction is
invoked todecrease the radius and redisplay the circle.

Another simple example is given below that shows how to use the motion
event, i.e. if the mouse is moved inside of a widget:

67
Example Program5 : MouseMove
from tkinter import *
def motion(event):
print("Mouse position: (%s %s)" % (event.x, event.y))
return
window = Tk()
display_message = "Python Programming and Machine Learning"
msg = Message(window, text = display_message)
msg.config(bg='lightgreen', font=('times', 24, 'italic'))
msg.bind('<Motion>',motion)
msg.pack()
mainloop()

Every time the mouse is moved in the Message widget, the position of the
mouse pointer will be printed.

3.8.1 Handling Mouse Button Event in Python

Example:
fromtkinter import *
fromtkinter.ttk import *
# creates tkinter window or root window
root = Tk()
# function to be called when button-2 of mouse is pressed
def pressed2(event):
print('Button-2 pressed at x = % d, y = % d'%(event.x, event.y))
# function to be called when button-3 of mouse is pressed

68
def pressed3(event):
print('Button-3 pressed at x = % d, y = % d'%(event.x, event.y))
## function to be called when button-1 is double clocked
defdouble_click(event):
print('Double clicked at x = % d, y = % d'%(event.x, event.y))
frame1 = Frame(root, height = 100, width = 200)
# Binding mouse buttons with the Frame widget
frame1.bind('<Button-2>', pressed2)
frame1.bind('<Button-3>', pressed3)
frame1.bind('<Double 1>', double_click)
frame1.pack()
root.mainloop()
Output:

69
3.8.2 Handling Key Press Event In Python

Example:

fromtkinter import *

fromtkinter.ttk import *

# function to be called when

# keyboard buttons are pressed

defkey_press(event):

key = event.char

print(key, 'is pressed')

# creates tkinter window or root window

root = Tk()

root.geometry('200x100')

# here we are binding keyboard

# with the main window


70
root.bind('<Key>', lambda a : key_press(a))

mainloop()

Output:

71
QUESTIONS

1. Write the Pyhton Program to create simple window.

2. Write a Python Program to create label, entry and button components


and arrange the components using Grid Layout.

3. Write a Python Program to validate user name and password.

4. Write a Python Program to display the basic shapes.

5. Write a Python program to create a following GUI design

6. Write the GUI program to create List Box for shopping cart.

7. Write a pyhton Program to create simple calculator.

8. Write a Python Program to add image on the button.

9. Write a Python progam to create simple application form.

10. Wrtite a Pyhton program to create check button for selecting multiple
hobbies.

72
SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

UNIT-IV - Python Programming – SCS1619


UNIT IV

DATABASE AND NETWORK

Database (using NoSQL): Connector Module –Cursor – Statements -


Exceptions in database.
Network connectivity: Socket module - Client – Server – Email – URL
Access

Data is very important for any organization to continue its operations.


The data may be related to employees in the organization or the operational
data like products information, raw material prices, sales information, profits
and losses. Without data, no organization will survive. Hence, data is very
important and it should never be lost.

DBMS

To store data, a file or database can be used. A file stores data in the
secondary storage device like hard disk, either in the text format or binary
format.

A database represents collection of data. Data can be stores in the database.


Once the data is stored in the database, various operations can be performed
on the data. For example, modifying the existing data, deleting the unwanted
data, or retrieving the data from the database and etc. To perform such

1
operations, a database comes with software. This is called a database
management system.

DBMS= Database + Software to manage the data

Example DBMS are MySQL, Oracle, Sybase,, SQL server etc.

Types of databases used with Python

4.1 DATABASE SUPPORT

 SQL

 NoSQL

As more and more data become available as unstructured or semi-


structured, the need of managing them through NoSql database increases.
Python can also interact with NoSQL databases in a similar way as is interacts
with Relational databases. In this chapter we will use python to interact with
MongoDB as a NoSQL database.

4.1.1 MongoDB

MongoDB stores data in JSON-like documents, which makes the database


very flexible and scalable.

Where to Use MongoDB?

 Big Data
 Content Management and Delivery

2
 Mobile and Social Infrastructure
 User Data Management
 Data Hub

download a free MongoDB database at https://www.mongodb.com.

PyMongo

Python needs a MongoDB driver to access the MongoDB database. In


this tutorial we will use the MongoDB driver "PyMongo".
We recommend that you use PIP to install "PyMongo".
PIP is most likely already installed in your Python environment.
Navigate your command line to the location of PIP, and type the following:
Download and install "PyMongo":

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-
32\Scripts>python -m pip install pymongo

Now you have downloaded and installed a mongoDB driver.

Where to Use MongoDB?

 Big Data
 Content Management and Delivery
 Mobile and Social Infrastructure
 User Data Management
3
 Data Hub

Test PyMongo

To test if the installation was successful, or if you already have "pymongo"


installed, create a Python page with the following content:

demo_mongodb_test.py:

import pymongo

Creating a Database

To create a database in MongoDB, start by creating a MongoClient object, then


specify a connection URL with the correct ip address and the name of the
database you want to create.

MongoDB will create the database if it does not exist, and make a connection to
it.

Example

Create a database called mydatabase

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = myclient["mydatabase"]
4
MongoDB waits until you have created a collection (table), with at least one
document (record) before it actually creates the database (and collection).

Creating a Collection

To create a collection in MongoDB, use database object and specify the name
of the collection you want to create.

MongoDB will create the collection if it does not exist.

Program

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

MongoDB waits until you have inserted a document before it actually


creates the collection.

Python MongoDB Insert Document

Insert Into Collection

To insert a record, or document as it is called in MongoDB, into a collection,


we use the insert_one() method.

The first parameter of the insert_one() method is a dictionary containing the


name(s) and value(s) of each field in the document you want to insert.

5
Example

Insert a record in the “Customers” Collection:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydict = { "name": "John", "address": "Highway 37" }


x = mycol.insert_one(mydict)

Insert Multiple Documents

To insert multiple documents into a collection in MongoDB, we use


theinsert_many() method.

The first parameter of the insert_many() method is a list containing


dictionaries with the data you want to insert:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mylist = [

6
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"},
{ "name": "Susan", "address": "One way 98"},
{ "name": "Vicky", "address": "Yellow Garden 2"},
{ "name": "Ben", "address": "Park Lane 38"},
{ "name": "William", "address": "Central st 954"},
{ "name": "Chuck", "address": "Main Road 989"},
{ "name": "Viola", "address": "Sideway 1633"}
]

x = mycol.insert_many(mylist)

Python MongoDB Find

In MongoDB we use the find and findOne methods to find data in a


collection.

Just like the SELECT statement is used to find data in a table in a MySQL
database.

Find One

To select data from a collection in MongoDB, we can use


the find_one()method.
7
The find_one() method returns the first occurrence in the selection.

Example

Find the first document in the customers collection:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

x = mycol.find_one()

print(x)

Output

{'_id': 1, 'name': 'John', 'address': 'Highway37'}

Find All

To select data from a table in MongoDB, we can also use the find() method.

The find() method returns all occurrences in the selection.

The first parameter of the find() method is a query object. In this example we
use an empty query object, which selects all documents in the collection.

8
Example

Return all documents in the "customers" collection, and print each document:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in mycol.find():

print(x)

{'_id': 1, 'name': 'John', 'address': 'Highway37'}


{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}

9
Filter the Result

When finding documents in a collection, you can filter the result by using a
query object.

The first argument of the find() method is a query object, and is used to limit
the search.

Example

Find document(s) with the address "Park Lane 38":

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": "Park Lane 38" }

mydoc = mycol.find(myquery)

for x in mydoc:
print(x)

output

{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}

10
Example

Find documents where the address starts with the letter "S" or higher:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": { "$gt": "S" } }

mydoc = mycol.find(myquery)

for x in mydoc:
print(x)

Output

{'_id': 5, 'name': 'Michael', 'address': 'Valley


345'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st
331'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow
Garden 2'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway
1633'}

11
Return Only Some Fields

The second parameter of the find() method is an object describing which


fields to include in the result.

This parameter is optional, and if omitted, all fields will be included in the
result.

Example

Return only the names and addresses, not the _ids:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1}):


print(x)

Output

{'name': 'John', 'address': 'Highway37'}


{'name': 'Peter', 'address': 'Lowstreet 27'}
{'name': 'Amy', 'address': 'Apple st 652'}
{'name': 'Hannah', 'address': 'Mountain 21'}
{'name': 'Michael', 'address': 'Valley 345'}
12
{'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'name': 'Betty', 'address': 'Green Grass 1'}
{'name': 'Richard', 'address': 'Sky st 331'}
{'name': 'Susan', 'address': 'One way 98'}
{'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'name': 'Ben', 'address': 'Park Lane 38'}
{'name': 'William', 'address': 'Central st 954'}
{'name': 'Chuck', 'address': 'Main Road 989'}
{'name': 'Viola', 'address': 'Sideway 1633'}

Sort the Result

Use the sort() method to sort the result in ascending or descending order.

The sort() method takes one parameter for "fieldname" and one parameter for
"direction" (ascending is the default direction).

Example

Sort the result alphabetically by

name: import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydoc =

mycol.find().sort("name")
13
for x in mydoc:
print(x)

OUTPUT

{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}


{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 1, 'name': 'John', 'address': 'Highway37'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}

Sort Descending

Use the value -1 as the second parameter to sort descending.

sort("name", 1) #ascending
sort("name", -1) #descending

Example

Sort the result reverse alphabetically by name:

14
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydoc = mycol.find().sort("name", -1)

for x in mydoc:
print(x)

Output

{'_id': 12, 'name': 'William', 'address': 'Central st 954'}


{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 1, 'name': 'John', 'address': 'Highway37'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}

Python MongoDB Delete Document

To delete one document, we use the delete_one() method.


15
The first parameter of the delete_one() method is a query object defining
which document to delete.

Note: If the query finds more than one document, only the first occurrence is
deleted.

Example

Delete the document with the address "Mountain 21":

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": "Mountain 21" }

mycol.delete_one(myquery)

Delete Many Documents

To delete more than one document, use the delete_many() method.

The first parameter of the delete_many() method is a query object defining


which documents to delete.

Example

Delete all documents were the address starts with the letter S:
16
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": {"$regex": "^S"} }

x = mycol.delete_many(myquery)

print(x.deleted_count, " documents deleted.")

output

2 documents deleted.
Delete All Documents in a Collection

To delete all documents in a collection, pass an empty query object to


the delete_many() method:

Example

Delete all documents in the "customers" collection:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

17
x = mycol.delete_many({})

print(x.deleted_count, " documents deleted.")

Output:

11 documents deleted

Python MongoDB Drop Collection

Delete Collection

You can delete a table, or collection as it is called in MongoDB, by using


the drop() method.

Example

Delete the "customers" collection:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mycol.drop()

The drop() method returns true if the collection was dropped successfully, and
false if the collection does not exist.
18
Python MongoDB Update

You can update a record, or document as it is called in MongoDB, by using


the update_one() method.

The first parameter of the update_one() method is a query object defining


which document to update.

Note: If the query finds more than one record, only the first occurrence is
updated.

Example

Change the address from "Valley 345" to "Canyon 123":

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": "Valley 345" }


newvalues = { "$set": { "address": "Canyon 123" } }

mycol.update_one(myquery, newvalues)

#print "customers" after the update:

19
for x in mycol.find():
print(x)

OUTPUT

{'_id': 1, 'name': 'John', 'address': 'Highway37'}


{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 5, 'name': 'Michael', 'address': 'Canyon 123'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway}

Update Many

To update all documents that meets the criteria of the query, use
the update_many() method.

Example

Update all documents where the address starts with the letter "S":

import pymongo

20
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myquery = { "address": { "$regex": "^S" } }


newvalues = { "$set": { "name": "Minnie" } }
x = mycol.update_many(myquery, newvalues)

print(x.modified_count, "documents updated.")

Output

2 documents updated.

Python MongoDB Limit

o limit the result in MongoDB, we use the limit() method.

The limit() method takes one parameter, a number defining how many
documents to return.

Consider you have a "customers" collection:

{'_id': 1, 'name': 'John', 'address': 'Highway37'}


{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
21
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway}

Example

Limit the result to only return 5 documents:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

myresult = mycol.find().limit(5)

#print the result:


for x in myresult:
print(x)

OUTPUT
{'_id': 1, 'name': 'John', 'address': 'Highway37'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}

22
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}

4.2 CURSOR CLASS

To work with MySQL in python, connector sub module of mysql module.

import mysql.connector;

to establish connection with MySQL database, we use the connect() method of


mysql.connector module as:

conn=mysql.connector.connect(host=’localhost’,database=’university’,user=’r
oot’, password=’***’)

The connect() method returns MySQLConnection class object ‘conn’.

The next step is to create cursor class object by calling the cursor() method on
‘conn’ object as:

cursor=con.cursor()

Cursor object is useful to execute SQL commands on the database.

it is done by execute() method of cursor object.

cursor.execute( sql querry)

23
example: cursor.execute(“select * from emptab”)

The resultant rows retirieved from the table are stored in cursor object. the
result can be fetched using fetchone() or fetchall() methods.

example: row = cursor.fetchone() # get 1 row

row = cursor.fetchall() # get all rows

Finally, the connection with MySQL can be closed by closing the cursor and
connection objects as:

cursor.close()

conn.close()

Program: A python program to retrieve and display all rows from the student
table:

import mysql.connector;

conn=mysql.connector.connect(host=’localhost’,database=’university’,user=’r
oot’, password=’***’)

cursor=con.cursor()

cursor.execute(“select * from stutab”)

row = cursor.fetchone()

while row is not None:

24
print(row)

row=cursor.fetchone()

cursor.close()

conn.close()

Output:

(1001, ‘Ajay’, 8.5)

(1002, ‘Alan’, 7.5)

(1001, ‘Joe’, 9.00)

4.3 EXCEPTIONS CLASSES

Interacting with a database is an error prone process, so we must always


implement some mechanism to handle errors.

Built in Exceptions

Table 4.1: Types of Exceptions

Exception Description
Warning Used for non-fatal issues. Must subclass

25
StandardError.
Error
Base class for errors. Must subclass
StandardError.
InterfaceError Used for errors in the database module, not the
database itself. Must subclass Error.
DatabaseError Used for errors in the database. Must subclass
Error.
DataError Subclass of DatabaseError that refers to errors in
the data.
OperationalError Subclass of DatabaseError that refers to errors
such as the loss of a connection to the database.
These errors are generally outside of the control of
the Python scripter.
Exception Description
IntegrityError Subclass of DatabaseError for situations that
would damage the relational integrity, such as
uniqueness constraints or foreign keys.
InternalError Subclass of DatabaseError that refers to errors
internal to the database module, such as a cursor
no longer being active.
ProgrammingError Subclass of DatabaseError that refers to errors
such as a bad table name and other things that can
safely be blamed on you.

26
27

You might also like