Gui and Web Programming Notes Unit 4 - Watermark
Gui and Web Programming Notes Unit 4 - Watermark
UNIT-IV
1
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Graphical User Interface (GUI) is nothing but a desktop application which helps you to
interact with the computers. They are used to perform different tasks in the desktops,
laptops and other electronic devices.
GUI apps like Text-Editors are used to create, read, update and delete different
types of files.
GUI apps like Chess and Solitaire are games which you can play.
GUI apps like Google Chrome, Firefox and Microsoft Edge are used to browse
through the Internet.
They are some different types of GUI apps which we daily use on the laptops or desktops.
Kivy
Python QT
wxPython
Tkinter
Jpython
Among all of these, Tkinter is preferred by learners and developers just because of how
simple and easy it is.
Q: Explain about different widgets in GUI(Graphical User Interface)
Tkinter
The primary GUI toolkit we will be using is Tk (Toolkit), Python’s default GUI,
We’ll access Tk from its Python interface called Tkinter (i.e. Tk interface ). It is
originally designed for the Tool Command Language (TCL). Due to Tk’s
popularity, it has been ported to a variety of other scripting languages, including
Perl (Perl/Tk), Ruby (Ruby/Tk), and Python (Tkinter).
Tkinter is actually an inbuilt Python module used to create simple GUI apps. It is
the most commonly used module for GUI apps in the Python.
We no need to worry about installation of the Tkinter module as it comes
with Python 3.6 version by default.
Consider the following diagram, it shows how an application actually executes in
Tkinter:
2
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Developing desktop based applications with python Tkinter is not a complex task. An
empty Tkinter top-level window can be created by using the following steps.
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.
Example
from tkinter import *
Example
import tkinter
window = tkinter.Tk()
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.
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to
build the python GUI applications.
SN Widget Description
1 Button The Button is used to add various kinds of buttons to the python
3
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
application.
2 Canvas The canvas widget is used to draw the shapes in your GUI.
3 Checkbutton The Checkbutton is used to display the CheckButton on the window.
The entry widget is used to display the single-line text field to the user.It
4 Entry
is commonly used to accept user values (Input Fields)
It can be defined as a container to which, another widget can be added
5 Frame
and organized.
A label is a text used to display some message or information about the
6 Label
other widgets.
7 ListBox The ListBox widget is used to display a list of options to the user.
8 Menubutton The Menubutton is used to display the menu items to the user.
9 Menu It is used to add menu items to the user.
10 Message The Message widget is used to display the message-box to the user.
The Radiobutton is different from a checkbutton. Here, the user is
11 Radiobutton provided with various options and the user can select only one option
among them.
12 Scale It is used to provide the slider to the user.
It provides the scrollbar to the user so that the user can scroll the
13 Scrollbar
window up and down.
It is different from Entry because it provides a multi-line text field to
14 Text
the user so that the user can write the text and edit the text inside it.
14 Toplevel It is used to create a separate window container.
15 Spinbox It is an entry widget used to select from options of values.
16 PanedWindow It is like a container widget that contains horizontal or vertical panes.
17 LabelFrame A LabelFrame is a container widget that acts as the container
This module is used to display the message-box in the desktop based
18 MessageBox
applications.
These widgets are the reason that Tkinter is so popular. It makes it really easy to
understand and use practically.
The Tkinter geometry specifies the method by using which; the widgets are represented on
display. The python Tkinter provides three geometry methods that help with positioning
our widgets.
4
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
The pack() widget is used to organize widget in the block, which mean it occupies the
entire available width. It’s a standard method to show the widgets in the window.
Example
Output:
The grid() geometry manager organizes the widgets in the tabular form. We can specify the
rows and columns as the options in the method call. We can also specify the column span
(width) or rowspan(height) of a widget.
This is a more organized way to place the widgets to the python application. The syntax to
use the grid() is given below.
Syntax
widget.grid(options)
A list of possible options that can be passed inside the grid() method is given below.
5
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Column
The column number in which the widget is to be placed. The leftmost column is
represented by 0.
row
The row number in which the widget is to be placed. The topmost row is
represented by 0.
Example
Output:
6
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
7
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
The place() geometry manager organizes the widgets to the specific x and y coordinates.
Syntax
widget.place(options)
Example
8
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Output:
The button widget is used to add various types of buttons to the python application. Python
allows us to configure the look of the button according to our requirements. Various
options can be set or reset depending upon the requirements.
We can also associate a method or function with a button which is called when the
button is pressed.
The syntax to use the button widget is given below.
Syntax
W = Button(parent, options)
9
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
10
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Example
#python application to create a simple button
b = Button(top,text = "Simple")
b.pack()
top.mainloop()
Output:
11
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Example
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("200x100")
def fun():
messagebox.showinfo("Hello", "Red Button clicked")
SN Option Description
1 Bd The represents the border width. The default width is 2.
2 Bg It represents the background color of the canvas.
3 confine It is set to make the canvas unscrollable outside the scroll region.
4 cursor The cursor is used as the arrow, circle, dot, etc. on the canvas.
5 height It represents the size of the canvas in the vertical direction.
6 highlightcolor It represents the highlight color when the widget is focused.
It represents the type of the border. The possible values are
7 relief
SUNKEN, RAISED, GROOVE, and RIDGE.
It represents the coordinates specified as the tuple containing the area
8 scrollregion
of the canvas.
9 width It represents the width of the canvas.
If it is set to a positive value. The canvas is placed only to the multiple
10 xscrollincrement
of this value.
If the canvas is scrollable, this attribute should be the .set() method of
11 xscrollcommand
the horizontal scrollbar.
12 yscrollincrement Works like xscrollincrement, but governs vertical movement.
If the canvas is scrollable, this attribute should be the .set() method of
13 yscrollcommand
the vertical scrollbar.
Example
from tkinter import *
top = Tk()
top.geometry("200x200")
#creating a simple canvas
c = Canvas(top,bg = "pink",height = "200")
c.pack()
top.mainloop()
Output:
13
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
top = Tk()
top.geometry("200x200")
Output:
SN Option Description
It represents the background color when the checkbutton is under
1 activebackground
the cursor.
It represents the foreground color of the checkbutton when the
2 activeforeground
checkbutton is under the cursor.
3 Bg The background color of the button.
4 Bitmap It displays an image (monochrome) on the button.
5 Bd The size of the border around the corner.
6 Command It is associated with a function to be called when the state of the
14
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
checkbutton is changed.
The mouse pointer will be changed to the cursor name when it is
7 Cursor
over the checkbutton.
It is the color which is used to represent the text of a disabled
8 disableforeground
checkbutton.
9 font It represents the font of the checkbutton.
10 fg The foreground color (text color) of the checkbutton.
It represents the height of the checkbutton (number of lines). The
11 height
default height is 1.
The color of the focus highlight when the checkbutton is under
12 highlightcolor
focus.
13 image The image used to represent the checkbutton.
This specifies the justification of the text if the text contains multiple
14 justify
lines.
The associated control variable is set to 0 by default if the button is
15 offvalue unchecked. We can change the state of an unchecked variable to
some other one.
The associated control variable is set to 1 by default if the button is
16 onvalue checked. We can change the state of the checked variable to some
other one.
17 padx The horizontal padding of the checkbutton
18 pady The vertical padding of the checkbutton.
The type of the border of the checkbutton. By default, it is set to
19 relief
FLAT.
20 selectcolor The color of the checkbutton when it is set. By default, it is red.
21 selectimage The image is shown on the checkbutton when it is set.
It represents the state of the checkbutton. By default, it is set to
normal. We can change it to DISABLED to make the checkbutton
22 state
unresponsive. The state of the checkbutton is ACTIVE when it is
under focus.
It represents the index of the character in the text which is to be
24 underline
underlined. The indexing starts with zero in the text.
It represents the associated variable that tracks the state of the
25 variable
checkbutton.
It represents the width of the checkbutton. It is represented in the
26 width
number of characters that are represented in the form of texts.
15
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Methods
The methods that can be called with the Checkbuttons are described in the following
table.
S Method Description
N
1 deselect() It is called to turn off the checkbutton.
2 flash() The checkbutton is flashed between the active and normal
colors.
3 invoke() This will invoke the method associated with the
checkbutton.
4 select() It is called to turn on the checkbutton.
5 toggle() It is used to toggle between the different Checkbuttons.
Example
from tkinter import
* top = Tk()
top.geometry("200x200")
chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack
()
16
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
chkbtn4.pack
()
chkbtn3.pack
()
top.mainloop(
)
Output:
17
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
18
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Example
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
submitbtn = Button(top, text = "Submit",activebackground = "pink",activeforeground = "blue").place(x
= 30, y = 170)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()
Output:
19
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
20
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
import tkinter as tk
from functools import partial
root = tk.Tk()
root.geometry('400x200+100+200')
root.title('Calculator')
number1 = tk.StringVar()
number2 = tk.StringVar()
labelResult = tk.Label(root)
labelResult.grid(row=7, column=2)
entryNum1 = tk.Entry(root, textvariable=number1).grid(row=1, column=2)
entryNum2 = tk.Entry(root, textvariable=number2).grid(row=2, column=2)
Output:
21
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Python Tkinter 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
w = Frame(parent, options)
SN Option Description
1 Bd It represents the border width.
2 Bg The background color of the widget.
The mouse pointer is changed to the cursor type set to different
3 Cursor
values like an arrow, dot, etc.
4 Height The height of the frame.
5 highlightbackground The color of the background color when it is under focus.
6 Highlightcolor The text color when the widget is under focus.
It specifies the thickness around the border when the widget is
7 highlightthickness
under the focus.
8 Relief It specifies the type of the border. The default value if FLAT.
9 Width It represents the width of the widget.
22
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Example
from tkinter import *
top = Tk()
top.geometry("140x100")
frame = Frame(top)
frame.pack()
leftframe = Frame(top)
leftframe.pack(side = LEFT)
rightframe = Frame(top)
rightframe.pack(side = RIGHT)
top.mainloop()
Output:
The Label is used to specify the container box where we can place the text or images.
This widget is used to provide the message to the user about other widgets used in the
python application.
There are the various options which can be specified to configure the text or the
part of the text shown in the Label.
23
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Syntax
w = Label (master, options)
SN Option Description
It specifies the exact position of the text within the size provided to the
1 Anchor widget. The default value is CENTER, which is used to center the text
within the specified space.
2 Bg The background color displayed behind the widget.
It is used to set the bitmap to the graphical object specified so that,
3 Bitmap
the label can represent the graphics instead of text.
4 Bd It represents the width of the border. The default is 2 pixels.
The mouse pointer will be changed to the type of the cursor specified,
5 Cursor
i.e., arrow, dot, etc.
6 Font The font type of the text written inside the widget.
7 Fg The foreground color of the text written inside the widget.
8 Height The height of the widget.
9 Image The image that is to be shown as the label.
It is used to represent the orientation of the text if the text contains
10 Justify multiple lines. It can be set to LEFT for left justification, RIGHT for
right justification, and CENTER for center justification.
11 Padx The horizontal padding of the text. The default value is 1.
12 Pady The vertical padding of the text. The default value is 1.
13 Relief The type of the border. The default value is FLAT.
This is set to the string variable which may contain one or more line
14 Text
of text.
The text written inside the widget is set to the control variable StringVar
15 textvariable
so that it can be accessed and changed accordingly.
We can display a line under the specified letter of the text. Set this
16 underline
option to the number of the letter under which the line will be
displayed.
17 Width The width of the widget. It is specified as the number of characters.
Instead of having only one line as the label text, we can break it to
18 wraplength
the number of lines where each line has the number of characters
specified to
24
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
this option.
Example 1
top = Tk()
top.geometry("400x250")
#creating label
uname = Label(top, text = "Username").place(x = 30,y = 50)
#creating label
password = Label(top, text = "Password").place(x = 30, y = 90)
Output:
Python TkinterListbox
The Listbox widget is used to display the list items to the user. We can place only
text items in the Listbox and all text items contain the same font and color.
The user can choose one or more items from the list depending upon the
configuration.
25
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
SN Option Description
1 Bg The background color of the widget.
2 Bd It represents the size of the border. Default value is 2 pixel.
3 Cursor The mouse pointer will look like the cursor type like dot, arrow,
etc.
4 Font The font type of the Listbox items.
5 Fg The color of the text.
It represents the count of the lines shown in the Listbox. The
6 Height
default value is 10.
7 highlightcolor The color of the Listbox items when the widget is under focus.
8 highlightthicknes The thickness of the highlight.
s
9 Relief The type of the border. The default is SUNKEN.
10 selectbackground The background color that is used to display the selected text.
It is used to determine the number of items that can be selected
11 selectmode from the list. It can set to BROWSE, SINGLE, MULTIPLE,
EXTENDED.
12 Width It represents the width of the widget in characters.
13 xscrollcommand It is used to let the user scroll the Listbox horizontally.
14 yscrollcommand It is used to let the user scroll the Listbox vertically.
Methods
There are the following methods associated with the Listbox.
S Method Description
N
1 activate(index) It is used to select the lines at the specified index.
It returns a tuple containing the line numbers of the
2 curselection() selected element or elements, counting from 0. If nothing is
selected, returns an empty tuple.
3 delete(first, last = None) It is used to delete the lines which exist in the given range.
4 get(first, last = None) It is used to get the list items that exist in the given range.
It is used to place the line with the specified index at the
5 index(i)
top of the widget.
It is used to insert the new lines with the specified number
6 insert(index, *elements)
of elements before the specified index.
7 nearest(y) It returns the index of the nearest line to the y coordinate
of
26
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Example 1
from tkinter import *
top = Tk()
top.geometry("200x250")
listbox = Listbox(top)
listbox.insert(1,"aiml ")
listbox.insert(2, "cse")
listbox.insert(3, "ds")
listbox.insert(4, "cs,iot")
lbl.pack()
listbox.pack()
top.mainloop()
Output:
27
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
top = Tk()
top.geometry("200x250")
#this button will delete the selected item from the list
28
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
lbl.pack()
listbox.pack()
btn.pack()
top.mainloop()
Output:
29
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
30
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Syntax
w = Menu(top, options)
SN Option Description
The background color of the widget when the widget is under the
1 activebackground
focus.
31
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
The width of the border of the widget when it is under the mouse.
2 activeborderwidth
The default is 1 pixel.
3 activeforeground The font color of the widget when the widget has the focus.
4 Bg The background color of the widget.
5 Bd The border width of the widget.
The mouse pointer is changed to the cursor type when it hovers the
6 cursor
widget. The cursor type can be set to arrow or dot.
7 disabledforeground The font color of the widget when it is disabled.
8 Font The font type of the text of the widget.
9 Fg The foreground color of the widget.
The postcommand can be set to any of the function which is called
10 postcommand
when the mourse hovers the menu.
11 relief The type of the border of the widget. The default type is RAISED.
12 image It is used to display an image on the menu.
The color used to display the checkbutton or radiobutton when
13 selectcolor
they are selected.
By default, the choices in the menu start taking place from position
14 tearoff 1. If we set the tearoff = 1, then it will start taking place from 0th
position.
Set this option to the title of the window if you want to change the
15 Title
title of the window.
Methods
32
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
options) index.
9 index(item) It is used to get the index of the specified menu item.
10 insert_seperator(index) It is used to insert a seperator at the specified index.
It is used to invoke the associated with the choice given at
11 invoke(index)
the specified index.
It is used to get the type of the choice specified by the
12 type(index)
index.
A top-level menu can be created by instantiating the Menu widget and adding the menu
items to the menu.
Example 1
top = Tk()
def hello():
print("hello!")
top.mainloop()
Output:
33
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Clicking the hello Menubutton will print the hello on the console while clicking the Quit
Menubutton will make an exit from the python application.
Example 2
from tkinter import Toplevel, Button, Tk, Menu
top = Tk()
menubar = Menu(top)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")
file.add_separator()
file.add_command(label="Exit", command=top.quit)
menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar, tearoff=0)
edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
34
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
menubar.add_cascade(label="Edit", menu=edit)
35
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
top.config(menu=menubar)
top.mainloop()
Output:
The Message widget is used to show the message to the user regarding the behaviour of the
python application. The message widget shows the text messages to the user which can not
be edited.
The message text contains more than one line. However, the message can only be shown in
the single font.
The syntax to use the Message widget is given below.
Syntax
w = Message(parent, options)
A list of possible options is given below.
SN Option Description
It is used to decide the exact position of the text within the space provided
1 Anchor to the widget if the widget contains more space than the need of the text.
The default is CENTER.
2 Bg The background color of the widget.
It is used to display the graphics on the widget. It can be set to any
3 Bitmap
graphical or image object.
4 Bd It represents the size of the border in the pixel. The default size is 2 pixel.
5 Cursor The mouse pointer is changed to the specified cursor type. The cursor
36
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Example
from tkinter import *
top = Tk()
top.geometry("100x100")
msg.pack()
top.mainloop()
Output:
37
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Python TkinterRadiobutton
SN Option Description
1 activebackground The background color of the widget when it has the focus.
2 activeforeground The font color of the widget text when it has the focus.
It represents the exact position of the text within the widget if the
3 anchor widget contains more space than the requirement of the text. The
default value is CENTER.
4 Bg The background color of the widget.
It is used to display the graphics on the widget. It can be set to
5 bitmap
any graphical or image object.
6 borderwidth It represents the size of the border.
This option is set to the procedure which must be called every-
7 command
time when the state of the radiobutton is changed.
The mouse pointer is changed to the specified cursor type. It can
8 cursor
be set to the arrow, dot, etc.
9 Font It represents the font type of the widget text.
10 Fg The normal foreground color of the widget text.
38
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
It represents the state of the radio button. The default state of the
21 state Radiobutton is NORMAL. However, we can set this to
DISABLED to make the radiobutton unresponsive.
23 textvariable It is of String type that represents the text displayed by the widget.
The default value of this option is -1, however, we can set this
24 underline
option to the number of character which is to be underlined.
39
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
We can wrap the text to the number of lines by setting this option
28 wraplength to the desired number so that each line contains only that number
of characters.
Methods
SN Method Description
It is used to flash the radiobutton between its active and normal colors few
2 flash()
times.
Example
def selection():
selection = "You selected the option " + str(radio.get())
label.config(text = selection)
top = Tk()
top.geometry("300x150")
radio = IntVar()
lbl = Label(text = "Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,command=selection)
R1.pack( anchor = W )
R2.pack( anchor = W )
R3.pack( anchor = W)
40
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
label = Label(top)
label.pack()
top.mainloop()
Output:
The scrollbar widget is used to scroll down the content of the other widgets like listbox,
text, and canvas. However, we can also create the horizontal scrollbars to the Entry widget.
Syntax
w = Scrollbar(top, options)
then the callback is called when the user releases the mouse
button.
It can be set to HORIZONTAL or VERTICAL depending upon
11 orient
the orientation of the scrollbar.
This option tells the duration up to which the button is to be
12 repeatdelay pressed before the slider starts moving in that direction
repeatedly. The default is 300 ms.
13 repeatinterval The default value of the repeat interval is 100.
We can tab the focus through this widget by default. We can set
14 takefocus
this option to 0 if we don't want this behavior.
15 troughcolor It represents the color of the trough.
16 width It represents the width of the scrollbar.
Methods
Example
from tkinter import *
top = Tk()
sb = Scrollbar(top)
sb.pack(side = RIGHT, fill = Y)
mainloop()
Output:
42
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
The Text widget is used to show the text data on the Python application. However, Tkinter
provides us the Entry widget which is used to implement the single line text box.
The Text widget is used to display the multi-line formatted text with various styles
and attributes. The Text widget is mostly used to provide the text editor to the user.
The Text widget also facilitates us to use the marks and tabs to locate the specific sections
of the Text. We can also use the windows and images with the Text as it can also be used
to display the formatted text.
The syntax to use the Text widget is given below.
Syntax
w = Text(top, options)
A list of possible options that can be used with the Text widget is given below.
SN Option Description
1 Bg The background color of the widget.
2 Bd It represents the border width of the widget.
The mouse pointer is changed to the specified cursor type, i.e.
3 Cursor
arrow, dot, etc.
The selected text is exported to the selection in the window
4 Exportselection manager. We can set this to 0 if we don't want the text to be
exported.
5 Font The font type of the text.
6 Fg The text color of the widget.
7 Height The vertical dimension of the widget in lines.
8 highlightbackground The highlightcolor when the widget doesn't has the focus.
9 highlightthickness The thickness of the focus highlight. The default value is 1.
10 Highlighcolor The color of the focus highlight when the widget has the focus.
43
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Methods
44
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
The tags are the names given to the separate areas of the text. The tags are used to
configure the different areas of the text separately. The list of tag-handling methods along
with the description is given below.
SN Method Description
tag_add(tagname, startindex, This method is used to tag the string present in
1
endindex) the specified range.
This method is used to configure the tag
2 tag_config
properties.
3 tag_delete(tagname) This method is used to delete a given tag.
tag_remove(tagname, startindex, This method is used to remove a tag from the
4
endindex) specified range.
Example
from tkinter import *
45
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
top = Tk()
text = Text(top)
text.insert(INSERT, "Name. .. ")
text.insert(END, "Salary. ... ")
text.pack()
top.mainloop()
Output:
Other GUIs
General GUI development using many of the abundant number of graphical toolkits that
exist under Python, but alas, that is for the future. As a proxy, we would like to present a
single simple GUI application written using four of the more popular and available toolkits
out there: Tix (Tk Interface eXtensions), Pmw (Python MegaWidgetsTkinter extension),
wxPython (Python binding to wxWidgets), and PyGTK (Python binding to GTK+).
Tix, the Tk Interface eXtension, is a powerful set of user interface components that
expands the capabilities of your Tcl/Tk and Python applications. Using Tix together with
Tk will greatly enhance the appearance and functionality of your application.
Example:
47
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
top = Tk()
top.tk.eval('package require Tix')
top.mainloop()
Output:
PMW (Python Mega Widgets) is a toolkit for building high -level widgets in Python using
the Tkinter module. This toolkit provides a frame work that contains a variety of widgets
richer than the one provided by Tkinter.
It basically helps the extend its longevity by adding more modern widgets to the GUI
Palette.This package is 100% written in Python, which turns out to be a cross -platform
48
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
widget library. Being highly configurable allows it to create additional widget collections by
extending the basic Tkinter widget core set.
PMW provides many interesting and complex widgets, including: About Dialog, Balloon,
Button Box, Combo Box, Combo Box Dialog, Counter, CounterDialog, Dialog, Entry
Field, Group, Labeled Widget, MenuBar, Message Bar, Message Dialog, Note BookR,
Note BookS, Note Book, Option Menu, Paned Widget, Prompt Dialog, RadioSelect,
Scrolled Canvas, Scrolled Field, ScrolledFrame, Scrolled Listbox, ScrolledText, Selection
Dialog, Text Dialog, and Time Counter.
Example:
from Tkinter import Button, END, Label, W
from Pmw import initialise, ComboBox, Counter
top = initialise()
lb = Label(top,
text='Animals (in pairs; min: pair, max: dozen)')
lb.pack()
qb = Button(top, text='QUIT',
command=top.quit, bg='red', fg='white')
qb.pack()
49
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
that you are not restricted to developing wxWidgets applications in C++. There are
interfaces to both Python and Perl.
There are other GUI development systems that can be used with Python. We present the
appropriate modules along with their corresponding window systems. Table represents the
GUI Systems Available for Python
50
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
51
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
WEB Programming:
Introduction
Wed Surfing with Python
Creating Simple Web Clients
Advanced Web Clients
CGI-Helping Servers Process Client Data
Building CGI Application
Advanced CGI
Web (HTTP) Servers
WEB PROGRAMMING
Web development is term for conceptualizing, creating, deploying and operating web
applications and application programming interfaces for the Web.
web development involves a frontend, everything that interacts with the client, and a
backend, which contains business logic and interacts with a database.
Easy to learn: Python is the most popular language for first-time learners for a
reason. The language relies on common expressions and whitespace, which
allows you to write significantly less code compared to some other languages like
Java or C++. Not only that, but it has a lower barrier of entry because it’s
comparatively more similar to your everyday language so you can easily
understand the code.
Rich ecosystem and libraries: Python offers a vast range of library tools and
packages, which allows you to access much pre-written code, streamlining your
application development time. For example, you have access to Numpy and
Pandas for mathematical analysis, Pygal for charting, and SLQALchemy for
composable queries. Python also offers amazing web frameworks like Django and
Flask, which we’ll dive into later in the article.
Fast prototyping: Because Python takes significantly less time to build your
projects compared to other programming languages, your ideas come to life a lot
faster, allowing you to gain feedback and iterate quickly. This quick development
time makes Python especially great for startups.
language is, Python is continuously updated with new features and libraries,
while also providing excellent documentation and community support. Especially
for new developers, Python provides extensive support and framework for one to
begin their developer journey.
Python web frameworks are only utilized in the backend for server-side technology,
aiding in URL routing, HTTP requests and responses, accessing databases, and web
security.
Lets take a look at a few operations involved in a web application using a web
framework:
URL Routing – Routing is the mechanism of mapping the URL directly to the
code that creates the web page.
Input form handling and validation – Suppose you have a form which takes
some input, the idea is to validate the data and then save it.
Output formats with template engine – A template engine allows the developers
to generate desired content types like HTML, XML, JSON.
Database connection – Database connection configuration and persistent data
manipulation through an ORM.
Web security – Frameworks give web security against cross-site request forgery
aka CSRF, sql injection, cross-site scripting and other common malicious attacks.
Session storage and retrieval – Data stored in the session storage gets cleared
when the page session ends.
Advantages Of Frameworks
1. Open-source
2. Good documentation
3. Efficient
4. Secure
5. Integration
Frameworks make it easier to reuse the code for common HTTP operations. They
structure the projects in a way so that the other developers with the knowledge of the
framework can easily maintain and build the application.
Django
Flask
Web2Py
Bottle
TurboGears
Pyramid
CubicWeb
CherryPy
TurboGears
Quixote
Django
Template engine
MVC-MVT architecture:
MVT is slightly different from MVC, Although Django takes care of the controller
part which is the code that controls the interactions between the model and the
view. And the template is HTML file mixed with Django template language.
Developer provides the model, view and the template. User then maps it to the url
and then the rest is done by django to serve it to the user.
Instagram
Mozilla Firefox
NASA
CherryPy
CherryPy allows us to use any type of technology for creating templates and data
access. It is still able to handle sessions, cookies, statics, file uploads and everything
else a web framework typically can.
TurboGears
55
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Flask
Flask is a popular Python web framework used for developing complex web
applications. The framework offers suggestions but doesn’t enforce any dependencies or
project layout.
Flask is flexible.
The framework aims to keep the core simple but extensible.
It includes many hooks to customize its behavior.
Integrated support for unit testing Restful request dispatching
Contains development server and debugger
Uses Jinja2 templating
Support for secure cookies
Unicode-based
Extensive documentation
Google App Engine compatibility
Extensions available to enhance features desired
Web2Py
56
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Written in Python, Web2Py is a free, open-source web framework for agile development
of secure database-driven web applications. It is a full-stack framework.
Bottle
Bottle is a fast, simple and lightweight WSGI micro web framework for Python web
applications. The framework has no other dependencies than the standard Python
library.
Templating
Access to form data, file uploads, cookies, headers etc.
Abstraction layer over the WSGI standard
A built-in development server that supports any other WSGI-capable HTTP server.
Pyramid
Some useful Python libraries for web development to keep note of:
If you ever need a web crawler to extract data for your application, Scrapy is
great for that. It’s a widely used library for scraping, data mining, automated
testing, and more.
Requests is a library that allows you to send HTTP requests easily, which is used
to communicate with an application, allowing you to get HTML pages or data
58
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Web programming refers to the writing, markup and coding involved in Web
development, which includes Web content, Web client and server scripting and network
security. The most common languages used for Web programming are XML, HTML,
JavaScript, Perl 5 and PHP.
The work associated in website design contain multiple areas: web programming,
database management, web design, web publishing, etc. Web development includes all
the codes that influence a website to run. We can separate the whole process of web
development into two categories:
Front-end
Back-end
Though frontend and backend web development are certainly distinct from each other,
they are also like two sides of the same coin. A complete website relies on each side
communicating and operating effectively with the other as a single unit. Both front-end
and back-end are equally important in web development.
The front-end or client-side of an application is the code responsible for everything the
user directly experiences on screen from text colors to buttons, images and navigation
menus. Some of the common skills and tools which are used by front-end developers
are listed below:
HTML/CSS/JavaScript
CSS preprocessors
Frameworks
Libraries
Git and Github
59
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
This time, Web clients are browsers, applications that allow users to seek documents on
the World Wide Web. On the other side are Web servers, processes that run on an
information provider's host computers. These servers wait for clients and their
document requests, process them, and return the requested data. As with most servers
in a client/server system, Web servers are designed to run "forever."
A user runs a Web client program such as a browser and makes a connection to a Web
server elsewhere on the Internet to obtain information.
Clients may issue a variety of requests to Web servers. Such requests may include
obtaining a Web page for viewing or submitting a form with data for processing. The
request is then serviced by the Web server, and the reply comes back to the client in a
special format for display purposes.
The "language" that is spoken by Web clients and servers, the standard protocol used
for Web communication, is called HTTP, which stands for Hyper Text Transfer Protocol.
HTTP is written "on top of" the TCP and IP protocol suite, meaning that it relies on TCP
and IP to carry out its lower-level communication functionality. Its responsibility is not
to route or deliver messages TCP and IP handle that but to respond to client requests
(by sending and receiving HTTP messages).
HTTP is known as a "stateless" protocol because it does not keep track of information
from one client request to the next, similar to the client/server architecture we have
seen so far. The server stays running, but client interactions are singular events
structured in such a way that once a client request is serviced, it quits. New requests
can always be sent, but they are considered separate service requests.
Because of the lack of context per request, you may notice that some URLs have a long
set of variables and values chained as part of the request to provide some sort of state
information. Another alternative is the use of "cookies" static data stored on the client
side which generally contain state information as well. In later parts of this chapter, we
will look at how to use both long URLs and cookies to maintain state information.
The Internet
The Internet is a moving and fluctuating "cloud" or "pond" of interconnected clients and
servers scattered around the globe. Communication between client and server consists
of a series of connections from one lily pad on the pond to another, with the last step
connecting to the server.
60
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Browser is only one type of Web client. Any application that makes a
request for data from a Web server is considered a "client." Yes, it is possible to create
other clients that retrieve documents or data off the Internet. One important reason to
do this is that a browser provides only limited capacity, i.e., it is used primarily for
viewing and interacting with Web sites.
Applications that use the urllib module to download or access information on the Web
[using either urllib.urlopen() or urllib.urlretrieve()] can be considered a simple Web
client. All you need to do is provide a valid Web address.
Simple Web surfing involves using Web addresses called URLs (Uniform Resource
Locators). Such addresses are used to locate a document on the Web or to call a CGI
program to generate a document for your client.
URLs are part of a larger set of identifiers known as URIs (Uniform Resource Identifiers).
This superset was created in anticipation of other naming conventions that have yet to
be developed.
A URL is simply a URI which uses an existing protocol or scheme (i.e., http, ftp, etc.) as
part of its addressing.
To complete this picture, we'll add that non-URL URIs are sometimes known as URNs
(Uniform Resource Names), but because URLs are the only URIs in use today, you really
don't hear much about URIs or URNs, save perhaps as XML identifiers.
prot_sch://net_loc/path;params?query#frag
61
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
net_loc can be broken down into several more components, some required, others
optional. The net_loc string looks like this:
user:passwd@host:port
The host name is the most important. The port number is necessary only if the Web
server is running on a different port number from the default.
62
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Q: Explain about different modules which are using in web development in python
Modules
Python supplies two different modules, each dealing with URLs in completely different
functionality and capacities.
1. urlparse
2. urllib
1. urlparse Module
The urlparse module provides basic functionality with which to manipulate URL
strings. These functions include urlparse(), urlunparse(), and urljoin()
urlparse.urlparse()
urlparse() breaks up a URL string into some of the major components described above.
It has the following syntax:
urlparse() parses urlstr into a 6-tuple (prot_sch, net_loc, path, params, query, frag).
Each of these components has been described above.
defProtSch indicates a default network protocol or download scheme in case one is not
provided in urlstr.allowFrag is a flag that signals whether or not a fragment part of a
URL is allowed.
Here is what urlparse() outputs when given a URL:
>>> urlparse.urlparse('http://www.python.org/doc/FAQ.html')
('http', 'www.python.org', '/doc/FAQ.html', '', '', '')
urlparse.urlunparse()
urlunparse() does the exact opposite of urlparse()it merges a 6-tuple (prot_sch, net_loc,
path, params, query, frag)urltup, which could be the output of urlparse(), into a single
URL string and returns it.
Accordingly, we state the following equivalence:
urlunparse(urlparse(urlstr)) urlstr
63
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
You may have already surmised that the syntax of urlunparse() is as follows:
urlunparse(urltup)
urlparse.urljoin()
The urljoin() function is useful in cases where many related URLs are needed, for
example, the URLs for a set of pages to be generated for a Web site. The syntax for
urljoin() is:
urljoin() takes baseurl and joins its base path (net_loc plus the full path up to, but not
including, a file at the end) with newurl. For example:
>>> urlparse.urljoin('http://www.python.org/doc/FAQ.html', \
... 'current/lib/lib.htm')
'http://www.python.org/doc/current/lib/lib.html'
urllib Module
urllib
local files.
Specifically, the functions of the urllib module are
designed to download data (from the Internet, local network, or local
host) using the aforementioned protocols.
Use of this module generally obviates the need for using the httplib, ftplib, and
gopherlib modules unless you desire their lower-level functionality.
The urllib module provides functions to download data from given URLs as well as
encoding and decoding strings to make them suitable for including as part of valid URL
strings.
1.urlopen(),
2.urlretrieve(),
3.quote(),
4.unquote(),
5.quote_plus(),
6.unquote_plus(), and
7.urlencode().
urllib.urlopen()
urlopen() opens a Web connection to the given URL string and returns a file-like object.
It has the following syntax:
urlopen(urlstr, postQueryData=None)
For all HTTP requests, the normal request type is "GET." In these cases, the query
string provided to the Web server (key-value pairs encoded or "quoted," such as the
string output of the urlencode() function[see below]), should be given as part of urlstr.
If the "POST" request method is desired, then the query string (again encoded) should
be placed in the postQueryData variable.
GET and POST requests are the two ways to "upload" data to a Web server.
65
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Finally, a geturl() method exists to obtain the true URL of the final opened destination,
taking into consideration any redirection that may have occurred.
urllib.urlretrieve()
urlretrieve() will do some quick and dirty work for you if you are interested in working
with a URL document as a whole. Here is the syntax for urlretrieve():
Rather than reading from the URL like urlopen() does, urlretrieve() will simply
download the entire HTML file located at urlstr to your local disk.
It will store the downloaded data into local file if given or a temporary file if not.
If the file has already been copied from the Internet or if the file is local, no subsequent
downloading will occur.
The quote*() functions take URL data and "encodes" them so that they are "fit" for
inclusion as part of a URL string.
In particular, certain special characters that are unprintable or cannot be part of valid
URLs acceptable to a Web server must be converted.
This is what the quote*() functions do for you. Both quote*() functions have the
following syntax:
66
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
quote(urldata, safe='/')
Characters that are never converted include commas, underscores, periods, and
dashes, as well as alphanumeric.
When calling quote*(), the urldata string is converted to an equivalent string that can
be part of a URL string.
The safe string should contain a set of characters which should also not be converted.
The default is the slash ( / ).
unquote*(urldata)
Calling unquote() will decode all URL-encoded characters in urldata and return the
resulting string.
unquote_plus() will also convert plus signs back to space characters.
urllib.urlencode()
The pairs are in "key=value" format and are delimited by ampersands ( & ).
Furthermore, the keys and their values are sent to quote_plus() for proper encoding.
Here is an example output from urlencode():
67
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Web browsers are basic Web clients. They are used primarily for searching and
downloading documents from the Web. Advanced clients of the Web are those
applications that do more than download single documents from the Internet.
One example of an advanced Web client is a crawler (aka spider, robot). These are
programs that explore and download pages from the Internet for different reasons, some
of which include:
● Indexing into a large search engine such as Google or Yahoo!
● Offline browsing downloading documents onto a local hard disk and rearranging
hyperlinks to create almost a mirror image for local browsing
● Downloading and storing for historical or archival purposes, or
● Web page caching to save superfluous downloading time on Web site revisits.
Introduction to CGI
CGI means the "Common Gateway Interface". CGI is one of the essential parts of
HTTP (Hyper-Text Transfer Protocol).
CGI is a set of standards that defines a standard way of passing information or web-
user requests to an application program and getting data back to forward it to users.
It is the exchange of information between the web server and a custom script. When the
users requested the web-page, the server sends the requested web-page.
The web server usually passes the information to all application programs that process
data and sends back an acknowledged message; this technique of passing data back-
and-forth between server and application is the Common Gateway Interface.
The main feature of HTML is in its hypertext capability, text that is in one way or
another highlighted to point to another document in a related context to the original.
Such a document can be accessed by a mouse click or other user selection mechanism.
These (static) HTML documents live on the Web server and are sent to clients when and
if requested.
68
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Browsing
What happens when a user clicks a hyperlink to browse a particular web-page or URL
(Uniform Resource Locator).
The steps are:
Browser contacts the HTTP web server for demanding the URL
Parsing the URL
Look for the filename
If it finds that file, a request is sent back
Web browser takes a response from the web server
As the server response, it either shows the received file or an error message.
Configuring CGI
69
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
HTML Header
2. For Example
3. Content-type: text/html\r\n\r\n
1. Content-type It is a MIME string that is used to define the format of the file being
returned.
5. Content-length: N This information is used to report the estimated download time for a file.
The CGI module provides the many functions to work with the cgi. We are defining
strict_parsing = False) –
It is used to parse a query in the environment. We can also parse it using a file,
for file uploads.The first argument is the input file, and the second argument is
parse_header(string) - It is used to parse the header. It permits the MIME header into
the main value and a dictionary of parameters.
test() - It is used to test a CGI script, and we can use it in our program. It will generally
write minimal HTTP headers.
#!/usr/bin/python
print("Content-type:text/html\r\n\r\n")
print('<html>')
print('<head>')
print('</head>')
print('<body>')
72
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
print('</body>')
print('</html>')
You must have come across many situations when you need to pass some information
from your browser to web server and ultimately to your CGI Program.
Most frequently, browser uses two methods two pass this information to web server.
These methods are GET Method and POST Method.
The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the?character as follows −
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web server
and it produces a long string that appears in your browser's Location: box.
Never use GET method if you have password or other sensitive information to pass to
the server. The GET method has size limitation: only 1024 characters can be sent in a
request string. The GET method sends information using QUERY_STRING header and
will be accessible in your CGI Program through QUERY_STRING environment variable.
You can pass information by simply concatenating key and value pairs along with any
URL or you can use HTML <FORM> tags to pass information using GET method.
This example passes two values using HTML FORM and submit button. We use same
CGI script hello_get.py to handle this input.
73
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Here is the actual output of the above form, you enter First and Last Name and then
click submit button to see the result.
First Name:
Submit
Last Name:
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code for a form with two checkboxes −
Select Subject
Maths Physics
CGI Applications
A CGI application is slightly different from a typical program. The primary differences
are in the input, output, and user interaction aspects of a computer program. When a
CGI script starts, it needs to retrieve the user-supplied form data, but it has to obtain
this data from the Web client, not a user on the server machine nor a disk file.
The output differs in that any data sent to standard output will be sent back to the
connected Web client rather than to the screen, GUI window, or disk file. The data sent
back must be a set of valid headers followed by HTML.
74
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
cgi Module
This class should be instantiated when a Python CGI script begins, as it will read in all
the pertinent user information from the Web client (via the Web server).
Once this object has been instantiated, it will consist of a dictionary-like object that has
a set of key-value pairs. The keys are the names of the form items that were passed in
through the form while the values contain the corresponding data.
They can be Field Storage objects (instances) as well as instances of a similar class
called Mini Field Storage, which is used in cases where no file uploads or multiple-part
form data is involved.
Mini Field Storage instances contain only the key-value pair of the name and the data.
Lastly, they can be a list of such objects. This occurs when a form contains more than
one input item with the same field name.
In order to play around with CGI development in Python, you need to first install a Web
server, configure it for handling Python CGI requests, and then give the Web server
access to your CGI scripts. Some of these tasks may require assistance from your
system administrator.
Just start up the most basic Web server, just execute it directly with Python:
$ python -m CGIHTTPServer
This will start a Web server on port 8000 on your current machine from the current
directory.
Then you can just create a Cgi-bin right underneath the directory from which you
started the server and put your Python CGI scripts in there.
Put some HTML files in that directory and perhaps some .py CGI scripts in Cgi-bin, and
you are ready to "surf" directly to this Web site with addresses looking something
75
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
likethese:
http://localhost:8000/friends.htm
http://localhost:8000/cgi-bin/friends2.py
<HTML><HEAD><TITLE>
Friends CGI Demo (static screen)
</TITLE></HEAD>
<BODY><H3>Friends list for: <I>NEW USER</I></H3>
<FORM ACTION="/cgi-bin/friends1.py">
<B>Enter your Name:</B>
<INPUT TYPE=text NAME=person VALUE="NEW USER" SIZE=15>
<P><B>How many friends do you have?</B>
<INPUT TYPE=radio NAME=howmany VALUE="0" CHECKED> 0
<INPUT TYPE=radio NAME=howmany VALUE="10"> 10
<INPUT TYPE=radio NAME=howmany VALUE="25"> 25
<INPUT TYPE=radio NAME=howmany VALUE="50"> 50
<INPUT TYPE=radio NAME=howmany VALUE="100"> 100
<P><INPUT TYPE=submit></FORM></BODY></HTML>
76
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
#!/usr/bin/env python
import cgi
reshtml = '''Content-Type: text/html\n
<HTML><HEAD><TITLE>
Friends CGI Demo (dynamic screen)
</TITLE></HEAD>
<BODY><H3>Friends list for: <I>%s</I></H3>
Your name is: <B>%s</B><P>
You have <B>%s</B> friends.
</BODY></HTML>'''
77
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
form = cgi.FieldStorage()
who = form['person'].value
howmany = form['howmany'].value
print reshtml % (who, who, howmany)
This script contains all the programming power to read the form input and process it,
as well as return the resulting HTML page back to the user.
First of all we define the message in a Unicode string. We assume your text editor can
78
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
only enter ASCII. Therefore the non-ASCII characters are input using the \u escape. In
practice the message can also be read from a file or from database.
The first output the CGI generates is the content-type HTTP header. It is very important
to declare here that the content is transmitted in the UTF-8 encoding so that the
browser can correctly interpret it.
Then output the actual message. Use the string's encode() method to translate the
string into UTF-8 sequences first.
print UNICODE_HELLO.encode('UTF-8')
#!/usr/bin/env python
CODEC = 'UTF-8'
UNICODE_HELLO = u'''
Hello!
\u00A1Hola!
\u4F60\u597D!
\u3053\u3093\u306B\u3061\u306F!
'''
79
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
There are various advantages of using CGI programming. Below are some of its
advantages.
o The CGI programs can work on almost any web server and the portable.
o They are portable.
o The CGIs can increase the dynamic communication in the web applications.
o The CGIs can also be profitable, if we use them in development; they reduce the
development costs and maintenance costs.
o The CGIs takes less time to process the requests.
80
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Advanced CGI
These include the use of cookies cached data saved on the client side multiple values for
the same CGI field and file upload using multipart form submissions.
the CGI specifications only allow two types of form encodings, "application/x-www-
formurlencoded" and "multipart/form-data." Because the former is the default, there
is never a need to state the encoding in the FORM tag like this:
But for multipart forms, you must explicitly give the encoding as:
This directive presents an empty text field with a button on the side which allows you to
browse your file directory structure for a file to upload.
When using multipart, your Web client's form submission to the server will look
amazingly like (multipart) e-mail messages with attachments.
Upload
TEXTAREA element is used when multiline text has to be passed to the CGI Program.
Here is example HTML code for a form with a TEXTAREA box −
<form action = "/cgi-bin/textarea.py" method = "post" target = "_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
82
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
</form>
The result of this code is the following form −
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Entered Text Content is %s</h2>" % text_content
print "</body>"
2. Multivalued Fields
The most common case is when you have a set of checkboxes allowing a user to select
from various choices.
Each of the checkboxes is labeled with the same field name, but to differentiate them,
each will have a different value associated with a particular checkbox.
When more than one checkbox is submitted, you will have multiple values associated
with the same key. In these cases, rather than being given a single MiniFieldStorage
instance for your data, the cgi module will create a list of such instances that you will
83
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
3. Cookies
HTTP protocol is a stateless protocol. For a commercial website, it is required to
maintain session information among different pages. For example, one user
registration ends after completing many pages. How to maintain user's session
information across all the web pages?
In many situations, using cookies is the most efficient method of remembering and
tracking preferences, purchases, commissions, and other information required for
better visitor experience or site statistics.
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The
browser may accept the cookie. If it does, it is stored as a plain text record on the
visitor's hard drive. Now, when the visitor arrives at another page on your site, the
cookie is available for retrieval. Once retrieved, your server knows/remembers what
was stored.
Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire
when the visitor quits the browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that sets the cookie. This may be
blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key and value pairs.
Setting up Cookies
It is very easy to send cookies to browser. These cookies are sent along with HTTP
Header before to Content-type field. Assuming you want to set UserID and Password as
cookies. Setting the cookies is done as follows −
#!/usr/bin/python
From this example, you must have understood how to set cookies. We use Set-
Cookie HTTP header to set cookies.
It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that
cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
Retrieving Cookies
It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment
variable HTTP_COOKIE and they will have following form −
key1 = value1;key2 = value2;key3 = value3....
85
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
The data are submitted to the server using multipart encoding and retrieved in the
same manner on the server side using the FieldStorage instance.
The only tricky part is in retrieving the uploaded file. In our application, we choose to
iterate over the file, reading it line by line.
It is also possible to read in the entire contents of the file if you are not wary of its size.
Web pages are a collection of data, including images, text files, hyperlinks, database
files etc., all located on some computer (also known as server space) on the Internet. A
web server is dedicated software that runs on the server-side.
When any user requests their web browser to run any web page, the web server places
all the data materials together into an organized web page and forwards them back to
the web browser with the help of the Internet.
This intercommunication of a web server with a web browser is done with the help of a
protocol named HTTP (Hypertext Transfer Protocol).
These stored web pages mostly use static content, containing HTML
documents, images, style sheets, text files, etc. However, web servers can serve static
as well as dynamic contents.
Web Servers also assists in emailing services and storing files. Therefore it also uses
SMTP (Simple Mail Transfer Protocol)
and FTP (File Transfer Protocol)
86
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
protocols to support the respective services. Web servers are mainly used in web
hosting or hosting the website's data and running web-based applications.
The hardware of the web servers are connected to the Internet that manages thedata
exchange facility within different connected devices. In contrast, the software
of web server software is responsible for controlling how a user accesses delivered files.
Typically, web server management is an ideal example of the client/server model.
Therefore, it is compulsory for all computers that host websites (whether with
state or dynamic web page content) to have web server software.
The term web server can denote server hardware or server software, or in most cases,
both hardware and software might be working together.
87
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
On the hardware side, a web server is defined as a computer that stores software and
another website raw data, such as HTML files, images, text documents, and JavaScript
files. The hardware of the web servers are connected to the web and supports the data
exchange with different devices connected to the Internet.
On the software side, a web server includes server software accessed through website
domain names. It controls how web users access the web files and ensures the supply
of website content to the end-user. The web server contains several components,
including an HTTP server.
o sending and receiving mails on Internet by using SMTP (Simple Mail transfer
Protocol);
o fetching requests for File Transfer Protocol (FTP) files; and
o designing, developing, and publishing websites.
Many Web servers, even the basic one, also support the server-side scripting technique.
Server-side scripting is a web development method used to employ scripts on a web
server that produces a customized response for each user. This technique operates on
the server machine and consists of an extensive feature set, including database access.
The server-side scripting process will have various scripting languages such ASP
, PHP
, Java
, JavaScript
, Python
, ruby
and many more. This technique also enables the HTML files to be created dynamically.
It the client request and returns the appropriate file, whether static or dynamically
generated by CGI.
The complexity of the handler determines the complexity of your Web server. The
Python standard library provides three different handlers.
Module Description
Provides the base Web server and base handler
BaseHTTPServer classes, HTTPServer and
BaseHTTPRequestHandler, respectively
Contains the SimpleHTTPRequestHandler class
SimpleHTTPServer
to perform GET and HEAD requests
CGIHTTPServer
Contains the CGIHTTPRequestHandler class to
process POST requests and perform CGI execution
89
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Related Modules
These are a list of modules which you may use for Web development.
Module/Package Description
Web Applications
robotparser
Parses robots.txt files for URL "fetchability" analysis
httplib Used to create HTTP clients
XML Processing
90
DEPARTMENT OF COMPUTER SCIENCEAND ENGINEERING
(AIML & DS) Python Programming R18
Web Servers
92