Python - Module-5 (1) 1
Python - Module-5 (1) 1
Module 5
Prepared By,
Rini Kurian
Assistant Professor ,MCA
• GUI Programming: Tkinter introduction, Tkinter and
Python Programming, Tk Widgets, Tkinter examples
• Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below.
• Tkinter: It is easiest to start with. Tkinter is Python's standard GUI (graphical user interface) package. It is the most commonly used toolkit
for GUI programming in Python.
• JPython: It is the Python platform for Java that is providing Python scripts seamless access o Java class Libraries for the local machine.
• wxPython: It is an open-source, cross-platform GUI toolkit written in C++. It is one of the alternatives to Tkinter, which is bundled with
Python.
• Kivy:Kivy is an OpenGL ES 2 accelerated framework for the creation of new user interfaces. It supports multiple platforms namely
Windows, MacOSX, Linux, Android iOS and Raspberry Pi. It is open source and comes with over 20 widgets in its toolkit.
Python GUI – tkinter
• It is the standard GUI toolkit for Python.
• Python offers multiple options for developing GUI (Graphical User Interface).
• Out of all the GUI methods, tkinter is the most commonly used method.
• Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.
Importing tkinter is same as importing any other module in the Python code. Note that the name of the module in Python 2.x is ‘Tkinter’ and
in Python 3.x it is ‘tkinter’.
tkinter methods
1 Tk(screenName=None, baseName=None, className=’Tk’, useTk=1) :
To change the name of the window, you can change the className to the desired one. The basic code used to create the main window
of the application is:
2
mainloop(): There is a method known by the name mainloop() is used when your application is ready to run. mainloop() is an
infinite loop used to run the application, wait for an event to occur and process the event as long as the window is not closed.
m.mainloop()
Basic GUI Application
• Dimensions
• Fonts
• Colors
• Cursors
• Anchors
• Bitmaps
Geometry Management
• All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing widgets
throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and place.
1. The pack() Method − This geometry manager organizes widgets in blocks before placing them in the parent widget.
2. The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget.
3. The place() Method − This geometry manager organizes widgets by placing them in a specific position in the parent widget.
Python - Tkinter pack() Method
This geometry manager organizes widgets in blocks before placing them in
the parent widget.
•expand − When set to true, widget expands to fill any space not otherwise
used in widget's parent.
•fill − Determines whether widget fills any extra space allocated to it by the
packer, or keeps its own minimal dimensions: NONE (default), X (fill only
horizontally), Y (fill only vertically), or BOTH (fill both horizontally and
vertically).
•side − Determines which side of the parent widget packs against: TOP
(default), BOTTOM, LEFT, or RIGHT.
Python - Tkinter grid() Method
Here is the list of possible options −
This geometry manager organizes widgets in a table-like structure
•column − The column to put widget in; default 0 (leftmost column).
in the parent widget.
•columnspan − How many columns widgetoccupies; default 1.
•ipadx, ipady − How many pixels to pad widget, horizontally and
vertically, inside widget's borders.
•padx, pady − How many pixels to pad widget, horizontally and
vertically, outside v's borders.
•row − The row to put widget in; default the first row that is still
empty.
•rowspan − How many rowswidget occupies; default 1.
•sticky − What to do if the cell is larger than widget. By default, with
sticky='', widget is centered in its cell. sticky may be the string
concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW,
compass directions indicating the sides and corners of the cell to
which widget sticks.
Python - Tkinter place() Method
This geometry manager organizes widgets by placing them in a specific
position in the parent widget .
A standard Tkinter widget used to take input from the user through the user interface. A simple box is provided where the user can input
text.
2. Check Button
A check button is a Tkinter GUI widget that presents to the user a set of predefined options. The user may select more than
one option.
3. Radio Button
A radio button is a Tkinter GUI widget that allows the user to choose only one of a predefined set of mutually exclusive
options.
4. Label
A Tkinter widget used to display simple lines of text on a GUI. Also very versatile, and can even be used to display images.
5. Menu
• The Tkinter Menu widget is used to create various types of menus in the GUI such as top-level menus, which are displayed right
under the title bar of the parent window. This is fairly complex widget, but essential in creating a modern and powerful GUI.
6. ComboBox
A special extension of Tkinter, the ttk module brings forward this widget. A combobox presents a drop down list of options
and displays them one at a time. Has a more modern approach than other similar widgets.
7. Canvas
• One of the more advanced Tkinter widgets. As the name suggests, it’s used to draw graphs and plots on. We can even display images on a
Canvas. It’s like a drawing board on which you can paint or draw anything.
from tkinter import *
root = Tk()
frame=Frame(root,width=300,height=300)
frame.pack(expand = True, fill=BOTH)
root.mainloop()
8. Scale
• The Tkinter Scale widget is used to implement a graphical slider to the User interface giving the user the option of picking
through a range of values. The Maximum and minimum values on the Scale can be set the programmer.
9. Scrollbar
• A useful widget in GUI’s, which allows you to scroll in a Tkinter window or enable scroll for certain widgets. Typically used when
you’re limited in space for your Tkinter window, but want more space for the widget (e.g Canvas).
10. Toplevel
• A widget in Tkinter that allows for the easy spawning of new Tkinter Windows. Toplevel is a better alternative to spawning
extra tkinter windows by using tk().
WEB DEVELOPMENT
WEB SURFING: CLIENT/ SERVER COMPUTING
• Definition: To navigate through the World Wide Web or Internet, usually by clicking with a
mouse
• Same as Client/ Server Architecture
• Web Client: Browsers, allow users to view documents on the WWW
• Web Servers: Processes that run on an information provider’s host computers
• Servers wait for clients and their document requests, process them and then return the
requested data.
• 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
• Web Client - Request
• Obtaining a Web Page for viewing
• Submitting a form with data for processing
• This request is then serviced by the web Server and reply comes back to the Client in a
special format for display purpose.
WEB CLIENT AND WEB SERVER
INTERNET
http://www.w3.org/Consortium/mission.html
This string uniquely identifies the web resource that is the W3C mission document. It also specifies the way to
access it, as illustrated here.
• The host (www.w3c.org) specifies the name of the server hosting the document, which is unique to each
server.
• The path is the relative pathname of the document relative to a special directory at the server called the web
server root directory.
• Relative URL
PYTHON WEB CLIENT TOOLS
• Web Client: Any application that makes a request for data from a Web Server.
• Web Browser is one type of Web client.
• Client Program uses:
• Viewing and interacting with Web Sites
• Download data
• Store data
• Manipulate data
• Transmit data to another location or application
urllib provides a high-level Web communication library, supporting the basic Web protocols,
HTTP, FTP, and Gopher, as well as providing access to 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.
The function urlopen() in module urllib.request is similar to the built-in function open() that is
used to open (local) files. There are three differences however:
2. It results in an HTTP request being sent to the web server hosting the content.
In the next example, we use function urlopen() to request and receive an HTML
document hosted at a server on the web:
>>> from urllib.request import urlopen
>>> response = urlopen('http://www.w3c.org/Consortium/facts.html')
>>> type(response)
<class 'http.client.HTTPResponse'>
The object returned by function urlopen() is of type HTTPResponse, which is a type
defined in Standard Library module http.client. Objects of this type encapsulate
the HTTP response from the server.
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 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: number of blocks read so far, the block size in bytes, and 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()
• Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default,
this function is intended for quoting the path section of the URL. The optional safe parameter specifies additional characters that
should not be quoted — its default value is '/'.
• >>> number = 6
• >>> final
'http://www/~foo/cgi-bin/s.py?name=joe mama&num=6'
• >>> urllib.quote(final)
'http:%3a//www/%7efoo/cgi-bin/s.py%3fname%3djoe%20mama%26num%3d6‘
• >>> urllib.quote_plus(final)
'http%3a//www/%7efoo/cgi-bin/s.py%3fname%3dj oe+mama%26num%3d6'
urllib.unquote() and urllib.unquote_plus()
• As you have probably guessed, the unquote*() functions do the exact opposite of the quote*() functionsthey convert all
characters encoded in the "%xx" fashion to their ASCII equivalents. The syntax of unquote*() is as follows:
• 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()
• urlencode(), added to Python back in 1.5.2, takes a dictionary of key-value pairs and encodes them to be included as part of a
query in a CGI request URL string. 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():
• >>> urllib.urlencode(aDict)
'name=Georgina+Garcia&hmdir=%7eggarcia'
parse 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(urlstr)
• urlparse() parses urlstr into a 6-tuple (prot_sch, net_loc, path, params, query, frag).
• >>> f=urlparse('http://python.org/')
• >>> f
• 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.
• >>> p=urlunparse(f)
• >>> p
'http://python.org/'
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 with newurl.
• For example:
• 'http://www.cwi.nl/%7Eguido/FAQ.html'
Web Servers
• The most common Web servers are Apache, Netscape, IIS, thttpd, Zeus, and Zope. In situations where these servers may
be overkill for your desired application, Python can be used to create simple yet useful Web servers.
• 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 http.server 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.
HANDLERS
• BaseHTTPRequestHandler: The most basic, plain, vanilla handler, named BaseHTTPRequestHandler, is found in the
BaseHTTPServer module, along with the base Web server. Other than taking a client request, no other handling is
implemented at all, so you have to do it all yourself