Unit-4 Python
Unit-4 Python
PYTHON PROGRAMMING
Course Code: CS721PE
C. RAJEEV
Assist. Prof.
CSE,
MRECW.
UNIT-4
UNIT - IV
GUI Programming: Introduction, Tkinter and Python Programming,
Brief Tour of Other GUIs, Related Modules and Other GUIs.
GUI apps like Text-Editors are used to create, read, update and delete different types of
files.
GUI apps like Sudoku, Chess and Solitaire are games which you can play.
2. JPython: It is the Python platform for Java that is providing Python scripts seamless
access o Java class Libraries for the local machine.
There are many other interfaces(Kivy ,Python QT) available for GUI. Among all of
these, Tkinter is preferred by a lot of learners and developers just because of how simple
and easy it is.
What Are Tcl, Tk, and Tkinter?
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).
4. Label is used to insert some objects into the window. Here, we are adding a Label with
some text.
pack() attribute of the widget is used to display the widget in a size it requires.
import tkinter
top = tkinter.Tk()
C.pack()
top.mainloop()
3. Scale widget:
Scale widget is used to implement the graphical slider to the python application so that
the user can slide through the range of values shown on the slider and select the one among
them.
We can control the minimum and maximum values along with the resolution of the scale.
Syntax
w = Scale(top, options)
A list of possible options is given below:
from_: It is used to represent one end of the widget range.
to: It represents a float or integer value that specifies the other end of the
range represented by the scale.
orient: It can be set to horizontal or vertical depending upon the type of the scale.
bd: The border size of the widget. The default is 2 pixel.
bg: The background color of the widget.
font: The font type of the widget text.
fg: The foreground color of the text
Ex:
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=100)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()
4. Label:
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.
Syntax:
w = Label (master, options)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of the widget.
bg: to set he normal background color.
bg to set he normal background color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the button.
width: to set the width of the button.
height” to set the height of the button.
Ex:
from tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()
relief
Specifies the appearance of a
decorative border around the label.
The default is FLAT.
5. Checkbutton:
This widget is used to display a number of options to a user as toggle buttons. The
user can then select one or more options by clicking the button corresponding to each
option. (similar to HTML checkbox input)
Ex: checkbutton
from tkinter import *
import messagebox
import tkinter
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1, offvalue
= 0, height=5, width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, offvalue =
0, height=5, width = 20)
C1.pack() C2.pack() top.mainloop()
6. Entry
The Entry widget is used to provide the single line text-box to the user to accept a
value from the user.
If you want to display multiple lines of text that can be edited, then you should use
the Text widget.
If you want to display one or more lines of text that cannot be modified by the user,
then you should use the Label widget.
8. Listbox:
The Listbox widget is used to display a list of items from which a
user can select a number of items.
9. Menu:
The goal of this widget is to allow us to create all kinds of menus
that can be used by our applications. The core functionality provides
ways to create three menu types: pop-up, top-level and pull-down.
Ex: frame widget
Ex: Listbox widget
root = Tk()
var = StringVar()
label.pack()
root.mainloop()
Ex: Message box widget
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def helloCallBack():
msg = messagebox.showinfo( “Say Hello", "Hello World")
B = Button(top, text = “Say Hello", command = helloCallBack)
B.place(x = 100,y = 100)
top.mainloop()
13. Radiobutton:
Set of buttons of which only one can be "pressed" (similar to
HTML radio input)
14. Scrollbar:
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.
15. Text
It 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 used to provide the text editor to the user.
Ex: Radio button
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text=“C", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
label = Label(root)
label.pack()
root.mainloop()
Ex: scroll bar:
root = Tk()
scrollbar = Scrollbar(root)
mainloop()
Ex: text
from tkinter import *
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")
root.mainloop()
17. 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.
Ex:
from tkinter import *
master = Tk()
w = Spinbox(master, from_=0, to=10)
w.pack()
mainloop()
Brief Tour of Other GUIs
four of the more popular and available toolkits out there:
1. Tix (Tk Interface eXtensions)
2. Pmw (Python MegaWidgets Tkinter extension)
3. wxPython (Python binding to wxWidgets) and
4. PyGTK (Python binding to GTK+).
The Tix module is already available in the Python standard library. You must
download the other toolkit, which are third party.
Pmw is just an extension to Tkinter, it is the easiest to install (just extract into
your site packages).
wxPython and PyGTK involve the download of more than one file and building.
It consists of a set of base classes and a library of flexible and extensible megawidgets
built on this foundation.
wxPython is Open Source, which means that it is free for anyone to use and the source
code is available for anyone to look at and modify. And anyone can contribute fixes or
enhancements to the project.
wxPython is a cross-platform toolkit. This means that the same program will run on
multiple platforms without modification.
Currently Supported platforms are Microsoft Windows, Mac OS X and macOS, and
Linux or other unix-like systems with GTK2 or GTK3 libraries.
In most cases the native widgets are used on each platform to provide a 100% native
look and feel for the application.
4. PyGTK (Python binding to GTK+):
It is popular frameworks in use for Linux because they are open-source and give
developers a powerful toolkit to design Graphical User Interfaces.
This time, Web clients are browsers, applications that allow users to find 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.
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.
on the other hand , A client program,, has the ability to do more it can not only
download data, but it can also store it, manipulate it, or perhaps even transmit it to
another location or application.
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.
Uniform Resource Locators:
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).
A URL is simply a URI which uses an existing protocol or scheme (i.e., http, ftp, etc.) as
part of its addressing.
Like street addresses, Web addresses have some structure. An American street address
usually is of the form "number street designation," i.e., 123 Main Street. It differs from
other countries, which have their own rules.
A URL uses the format:
prot_sch://net_loc/path;params?query#frag
Again, 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
Of the four, the host name is the most important for running web server.
The port number is necessary only if the Web server is running on a different port number
from the default.
User names and passwords are used only when making FTP connections.
To deal with URLs in completely different functionality and capacities. Python supplies two
different modules,. One is urlparse, and the other is urllib.
1. urlparse Module:
The urlparse module provides basic functionality with which to manipulate URL strings.
These functions include-
1. urlparse(),
2. urlunparse(), and
3. urljoin()
1. urlparse.urlparse():
urlparse() breaks up a URL string into some of the major components(prot_sch,
net_loc, path, params, query, frag).
It has the following syntax:
urlparse(urlstr, defProtSch=None, allowFrag=None)
urlparse() parses urlstr into a 6-tuple (prot_sch, net_loc, path, params, query,
frag)
defProtSch indicates a default network protocol or download scheme in case one is not
provided in urlstr.allowFrag.
urlstr.allowFrag is a flag that signals whether or not a fragment part of a URL is allowed.
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 is a Python module that can be used for opening URLs(Uniform Resource Locators). It
defines functions and classes to help in URL actions.
Urllib is a package that collects several modules for working with URLs, such as:
urllib.request for opening and reading.
urllib.parse for parsing URLs
urllib.error for the exceptions raised
urllib.robotparser for parsing robot.txt files
If urllib is not present in your environment, execute the below code to install it.
pip install urllib
urllib.urlopen()
urlopen() opens a Web connection to the given URL string and returns a file-like object.
syntax:
urlopen(urlstr, postQueryData=None)
urlopen() opens the URL pointed to by urlstr. If no protocol or download scheme is given, or
if a "file“ scheme is passed in, urlopen() will open a local file.
For all HTTP requests, the normal request type is "GET." In these cases, the query string
provided to the Web, should be given as part of urlstr.
If the "POST" request method is desired, then the query string should be placed in the
postQueryData variable.
GET and POST requests are the two ways to "upload" data to a Web server. When a
successful connection is made, urlopen() returns a file-like object as if the destination was
a file opened in read mode.
for example, if our file object is f, then our "handle" would support the expected read
methods such as f.read(), f.readline(), f.readlines(), f.close(), and f.fileno().
urllib.urlretrieve():
Syntax:
urlretrieve(urlstr, localfile=None, downloadStatusHook=None)
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 localfile 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 downloadStatusHook, if provided, is a function that is called after each block of data
has been downloaded and delivered.
It is called with the following three arguments:
1. number of blocks read so far,
2. the block size in bytes, and
3. the total (byte) size of the file.
This is very useful if you are implementing "download status" information to the user in a
text-based or graphical display.
urlretrieve() returns a 2-tuple, (filename, mime_hdrs).
filename is the name of the local file containing the downloaded data.
mime_hdrs is the set of MIME headers returned by the responding Web server.
urllib.quote() and urllib.quote_plus():
The quote() functions take URL data and "encodes" them so that they are "fit" for
inclusion as part of a URL string.
Syntax:
quote(urldata, safe='/')
Characters that are never converted include commas, underscores, periods, and dashes,
and alphanumerics. All others are subject to conversion.
In particular, the disallowed characters(?,!, spaces) are changed to their hexadecimal
ordinal equivalents prepended with a percent sign (%), i.e., "%xx" where "xx" is the
hexadecimal representation of a character's ASCII value.
Ex:
>>> import urllib
>>> urllib.quote('Hello World@Python2')
'Hello%20World%40Python2‘
When calling quote*(), the urldata string is converted to an equivalent string that can be
part of a URL string.
CGI is used as an interface between the web server and the additionally installed
applications generating dynamic web content. These applications are called CGI scripts
and are written in different script and programming languages such as PHP, Perl, Python,
etc.
CGI allows CGI programs process HTML forms or other data coming from clients,
and then it allows the CGI programs send a response back to the client
.
The response can be HTML documents, GIF files, video clips, or any data the client
browser can view. This makes your web pages interactive with the user.
When a client requests a document from a server, the server finds the file and sends it to the
client.
However, if a client requests a CGI program, the server simply acts as an intermediary
between the client and the CGI program.
what happens when a client requests a CGI process?
1. The client sends a request to the server running on your machine. The request might be
for a document, or like the contents of an HTML form.
If the request is for a regular document (such as an HTML document or a .GIF file), the
server sends that document directly back to the client.
If the request is data intended for an external application, then the server needs to use CGI
to run that application.
For example, the client's request might be to search a database. The CGI application
takes the search criteria, searches the database, then sends the results back to the client.
2. When a server receives a request that must be handled by an external application
(a CGI request) that server creates a copy of itself.
This second process is called the CGI process because it is the process in which the
CGI program will run.
The CGI process has all the same communication pathways that the server process
has. The only purpose for the CGI process is to set up communications between the
CGI program and the server.
3. The CGI program responds to the client.
The CGI program takes the data that the server provides through environment
variables, standard input, or command-line arguments.
It processes the data, contacts any external services it needs to, and then sends a
response to the server by way of the data pathways using standard output.
The server then takes the program's response and sends it back to the client software.
Your program can output any type of data it needs to, including HTML, GIFs, or
JPEGs.
CGI applications:
CGI applications that create the HTML are usually written in one of many higher-
level programming languages that have the ability to accept user data, process it, and
return HTML back to the server.
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. If it is not ,an error
will occur because Web clients is a browser, it understand only valid HTTP data (i.e., MIME
headers and HTML).
cgi Module
There is one primary class in the cgi module i.e., the FieldStorage class.
This class should be instantiated when a Python CGI script begins, as it will read in all the
relevant 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.
These values themselves can be one of three objects. They can be
FieldStorage objects (instances)
MiniFieldStorage, which is used in cases where no file uploads or multiple-part form
data is involved. MiniFieldStorage 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.
For simple Web forms, you will usually find all MiniFieldStorage instances.
Building CGI Applications:
1. Setting Up a Web Server
2. Creating the Form Page
3. Generating the Results Page
4. Fully Interactive Web sites
If you want a real Web server, you will likely download and install Apache. There are
Apache plug-ins or modules for handling Python CGI.
If you want to 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 like these:
http://localhost:8000/friends.htm
http://localhost:8000/cgi-bin/friends2.py
2. Creating the Form Page
This HTML file (friends.html) presents a form to the user with an empty field for the
user's name and a set of radio buttons for the user to choose from.
1 <HTML><HEAD><TITLE> As you can see in the code,
2 Friends CGI Demo (static screen) the form contains two input
3 </TITLE></HEAD> variables: person and how
4 <BODY><H3>Friends list for: <I>NEW USER</I></H3> many. The values of these two
5 <FORM ACTION="/cgi-bin/friends1.py">
fields will be passed to our
6 <B>Enter your Name:</B>
CGI script, friends1.py.
7 <INPUT TYPE=text NAME=person VALUE="NEW USER" SIZE=15>
8 <P><B>How many friends do you have?</B>
9 <INPUT TYPE=radio NAME=howmany VALUE="0" CHECKED> 0
10 <INPUT TYPE=radio NAME=howmany VALUE="10"> 10
11 <INPUT TYPE=radio NAME=howmany VALUE="25"> 25
12 <INPUT TYPE=radio NAME=howmany VALUE="50"> 50
13 <INPUT TYPE=radio NAME=howmany VALUE="100"> 100
14 <P><INPUT TYPE=submit></FORM></BODY></HTML>
friends.htm in a client
Friends form page in IE6 on Win32 (friends.htm)
3.Generating the Results Page:
The input is entered by the user and the "Submit" button is pressed.
When this occurs, the script in, friends1.py, is executed via CGI.
This CGI script grabs the person and how many fields from the form and uses that data
to create the dynamically generated results screen.
1 #!/usr/bin/env python(friends1.py)
2
3 import cgi
4
5 reshtml = '''Content-Type: text/html\n
6 <HTML><HEAD><TITLE>
7 Friends CGI Demo (dynamic screen)
8 </TITLE></HEAD>
9 <BODY><H3>Friends list for: <I>%s</I></H3>
10 Your name is: <B>%s</B><P>
11 You have <B>%s</B> friends.
12 </BODY></HTML>'''
13
14 form = cgi.FieldStorage()
15 who = form['person'].value
16 howmany = form['howmany'].value
17 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.
assuming the user typed in "erick allen" as the name and clicked on the "10 friends" radio
button.
4. Fully Interactive Web sites:
A user enters his or her information from the form page. We then process the data and
output a results page.
Now, we will add a link to the results page that will allow the user to go back to the form
page, but rather than presenting a blank form, we will fill in the data that the user has
already provided.
Advanced CGI
These advanced CGI 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.
Using Cookies in CGI
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?
When 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 −
This produces the following result for the cookies set by above script −
User ID = XYZ
Password = XYZ123
File Upload:
To upload a file, the HTML form must have the enctype attribute set to multipart/form-data.
The input tag with the file type creates a "Browse" button.
Here is the script save_file.py to handle file upload −
Multivalued Fields:
how to process fields with multiple values.
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.
As you know, the data from the user are sent to the server in key-value pairs during
form submission.
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 iterate over to obtain the different values.
Web (HTTP) Servers:
An HTTP web server is nothing but a process that is running on your machine and does
exactly two things:
1- Listens for incoming http requests on a specific TCP socket address (IP address
and a port number)
2- Handles this request and sends a response back to the user.
Creating Web Servers in Python:
In python 2,To create a Web server, a base server and a "handler" are required.
The base (Web) server is a boilerplate item, a must have. Its role is to perform the
necessary HTTP communication between client and server.
The base server class is (appropriately) named HTTPServer and is found in the
BaseHTTPServer module.
The handler is the piece of software that does the majority of the "Web serving."
It processes 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:
HEAD requests.
module, which takes the SimpleHTTPRequestHandler and adds support for POST
requests. It has the ability to call CGI scripts to perform the requested processing and
Module Description
1. BaseHTTPServer Provides the base Web server and base handler classes,
HTTPServer and BaseHTTPRequestHandler, respectively.
I mentioned earlier, First a web server is a process that listens to incoming requests on
specific TCP address. TCP address is identified by an ip address and a port number.
Second, a web server also needs to be told how to handle incoming requests.
These incoming requests are handled by special handlers. You can think of a web
server as a dispatcher, a request comes in, the http server inspects the request and
dispatches it to a designated handler.
Ex: Creating a webserver
import http.server
import socketserver
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
PORT stores the value of 8080, then the server will be listening on incoming requests on
that port.
Serve_forever is a method on the TCPServer instance that starts the server and begins
listening and responding to incoming requests.
save this file as server.py in the same directory as index.html
<html>
<head>
<title>Python is awesome!</title>
</head>
<body>
<h1>Afternerd</h1>
<p>Congratulations! The HTTP Server is working!</p>
</body>
</html>
In that directory, start the web server:
$ python server.py
serving at port 8080
Now we have an HTTP server that is listening on any interface at port 8080 waiting for
incoming http requests.
Open your browser and type localhost:8080 in the address bar.