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

Python - Module-5 (1) 1

The document discusses various GUI programming and web development topics in Python including Tkinter for GUI creation, web clients and servers, and common Tkinter widgets like Entries, Labels, Menus, and Canvas. It provides examples of how to create basic GUI applications using Tkinter by importing the module, creating a main window, adding widgets, and applying event triggers. Common attributes, geometry managers, and example Tkinter widgets are also outlined.

Uploaded by

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

Python - Module-5 (1) 1

The document discusses various GUI programming and web development topics in Python including Tkinter for GUI creation, web clients and servers, and common Tkinter widgets like Entries, Labels, Menus, and Canvas. It provides examples of how to create basic GUI applications using Tkinter by importing the module, creating a main window, adding widgets, and applying event triggers. Common attributes, geometry managers, and example Tkinter widgets are also outlined.

Uploaded by

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

GUI Programming &Web Development

Module 5

Prepared By,
Rini Kurian
Assistant Professor ,MCA
• GUI Programming: Tkinter introduction, Tkinter and
Python Programming, Tk Widgets, Tkinter examples

• Web Development: Python Web clients tools, Web


Clients, Web Servers, Web Services.
Graphical User Interfaces (GUIs)
• Graphical User Interfaces (GUIs) are one of the most important parts of any web application. Some would say the most important part, since
today’s sophisticated users are quick to abandon applications with poor usability. The same is true for Python applications, as well.

• 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.

• It is a standard Python interface to the Tk GUI toolkit shipped with Python.

• Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.

To create a tkinter app:


• Importing the module – tkinter
• Create the main window (container)
• Add any number of widgets to the main window
• Apply the event Trigger on the widgets.

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 create a main window, tkinter offers a method

‘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

Standard Attributes for GUI

• 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.

Here is the list of possible options −

•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 .

Here is the list of possible options −


•anchor − The exact spot of widget other options refer to: may be N, E,
S, W, NE, NW, SE, or SW, compass directions indicating the corners and
sides of widget; default is NW (the upper left corner of widget)
•bordermode − INSIDE (the default) to indicate that other options refer
to the parent's inside (ignoring the parent's border); OUTSIDE otherwise.
•height, width − Height and width in pixels.
•relheight, relwidth − Height and width as a float between 0.0 and 1.0, as
a fraction of the height and width of the parent widget.
•relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0,
as a fraction of the height and width of the parent widget.
•x, y − Horizontal and vertical offset in pixels.
Ttk & Tkinter Widgets

There are various controls, such as buttons,


labels, scrollbars, radio buttons, and text
boxes used in a GUI application.

These little components or controls of


Graphical User Interface (GUI) are known
as widgets in Tkinter.
1. Entry

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)

canvas = Canvas(frame,bg='white', width = 300,height = 300)

coordinates = 20, 50, 210, 230


arc = canvas.create_arc(coordinates, start=0, extent=250, fill="blue")
arc = canvas.create_arc(coordinates, start=250, extent=50, fill="red")
arc = canvas.create_arc(coordinates, start=300, extent=60, fill="yellow")

canvas.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 – The language spoken by Web Client and Servers.


The standard protocol used for Web communication
HTTP is written on TCP and IP Protocol suite to carry out its lower- level communication needs
HTTP –is a stateless protocol
Raw data moving with this protocol
Additional level of security can be achieved using SSL or any other encryption
Firewalls help fight against unauthorized access to a corporate network by blocking known entry points
Proxy Servers are tools that can work along side firewalls
Forward Proxy
Reverse Proxy
INTERNET
“Plumbing” of the WWW
In order to request a resource on the web, there must be a way to identify it. In other words,
every resource on the web must have a unique name. Furthermore, there must be a way to
locate the resource (i.e., find out which computer on the Internet hosts the resource).
Therefore, the web must have a naming and locator scheme that allows a web client to identify
and locate resources. Once a resource is located, there needs to be a way to request the
resource. Sending a message like “Hey dude, get me that mp3!” is just not going to fly.
The client and server programs must communicate using an agreed-upon protocol that specifies
precisely how the web client and the web server are supposed to format the request message
and the reply message, respectively.
Web pages are a critical resource on the web. They contain formatted information and data and
also hyperlinks that enable web surfing. In order to specify the format of a web page and
incorporate hyperlinks into it, there needs to be a language that supports formatting instructions
and hyperlink definitions.
These three components —the naming scheme, the protocol, and the web publishing
language— were all developed by Berners-Lee and are the technologies that really define the
WWW.
Naming Scheme: Uniform Resource Locator
In order to identify and access a resource on the web, each resource must have a unique identifier. The
identifier is called the Uniform Resource Locator (URL). The URL not only uniquely identifies a resource but
also specifies how to access it, just as a person’s address can be used to find the person. For example, the
mission statement of the W3C is hosted on the consortium’s web site, and its URL is the string

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 scheme specifies how to access the resource.

• 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

• Web client: Application that use urllib module to download or access


information on the web.
• urllib using
• urllib.urlopen()
• urllib.urlretrieve ()
Module urllib.request
We typically use browsers to access web pages on the web. A browser is just one type of web
client, however; any program can act as a web client and access and download resources on
the web.

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:

1. urlopen() takes as input a URL rather than a local file pathname.

2. It results in an HTTP request being sent to the web server hosting the content.

3. It returns a complete HTTP response.


Module urllib.request

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():

• 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: 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 '/'.

• >>> name = 'joe mama'

• >>> number = 6

• >>> base = 'http://www/~foo/cgi-bin/s.py’

• >>> final = '%s?name=%s&num=%d' % (base, name, number)

• >>> 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():

• >>> aDict = { 'name': 'Georgina Garcia', 'hmdir': '~ggarcia' }

• >>> 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).

• >>> from urllib.parse import urlparse

• >>> f=urlparse('http://python.org/')

• >>> f

ParseResult(scheme='http', netloc='python.org', path='/', params='', query='', fragment='')


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.

• >>> from urllib.parse import urlunparse

• >>> 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(baseurl, newurl, allowFrag=None)

• urljoin() takes baseurl and joins its base path with newurl.

• For example:

• >>> from urllib.parse import urljoin

• >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')

• '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.

• Creating Web Servers in Python

• 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

• SimpleHTTPRequestHandler: The SimpleHTTPRequestHandler, available in the SimpleHTTP-Server module,


builds on BaseHTTPRequestHandler by implementing the standard GET and HEAD requests in a fairly
straightforward manner

• CGIHTTPRequestHandler: CGIHTTPRequestHandler, available in the CGIHTTPServer 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 can send the generated HTML back to the client.
Simple Web Server in Python
WEB SERVICES
Web Services
• Web service is a software system designed to
support interoperable machine-to-machine
interaction over a network.
• It has an interface described in a machine-
processable format, Web Services Description
Language (WSDL).
Web Services
• Python 3 comes with two different libraries for interacting with
http web services:
• http.client is a low-level library that implements rfc 2616, the
http protocol.
• urllib.request is an abstraction layer built on top of http.client. It
provides a standard API for accessing both http and ftp servers,
automatically follows http redirects, and handles some common
forms of http authentication.
How to access various Web Services in Python

• API : Application Programming Interface


• An API is a protocol intended to be used as an interface by software
components to communicate with each other. An API is a set of
programming instructions and standards for accessing.
• With API's applications talk to each other without any user knowledge or
intervention. web based software applications
• Often, companies like Google, Vimeo and Twitter releases it's API to the
public so that developers can develop products that are powered by its
service.
• It is important to know that an API is a software-to-software interface, not a
user interface.
• API Key
• Many services on the Internet (such as Twitter, Facebook..) requires that
you have an "API Key". An application programming interface key (API
key) is a code passed in by computer programs calling an API to identify
the calling program, its developer, or its user to the Web site.
• When we interact with an API we often get the responses in a form called
JSON.
• JSON (JavaScript Object Notation) is a compact, text based format for
computers to exchange data. It's built on two structures: - A collection of
name/value pairs - An ordered list of values.
• JSON take these forms: objects, array, value, string, number
Accessing Web Services

• To get started with accessing web services, we first need to


find an URL to call the API.
• The URL that we need can often be found on the company's
website, at the same place where the API documentation is.
As an example:
• YouTube
http://gdata.youtube.com/feeds/api/standardfeeds/most_pop
ular?v=2&alt=json
• What modules do I need?
• The modules I usually use when working with JSON are:
• requests
• json (or simplejson)
• pprint
• Once you know which URL you need and have imported
the necessary modules, we can use the request module
to get the JSON feed.
• Converting the data
• This will take the JSON string and make it a
dictionary: json.loads(r.text)
• Looping through the result
• We know have a python dictionary and we can start
using it to get the results we want.
Example: Yahoo! Finance Stock Quote
Server
• If you visit the Web site and pull up a quotation for any stock, you will
find a Uniform Resource Locator (URL) link under the basic quote
data labeled "Download Data," which lets users download a CSV file
suitable for importing into Microsoft Excel
• http://finance.yahoo.com/d/quotes.csv?s=GOOG&f=sl1d1t1c1ohgv&e
=.csv
• If your browser's MIME settings are set correctly, your browser will
actually launch Excel with the resulting data.
from time import ctime
from urllib.request import urlopen
ticks = ('YHOO', 'GOOG', 'EBAY', 'AMZN')
URL = 'http://quote.yahoo.com/d/quotes.csv?s=%s&f=sl1c1p2'
print ('\nPrices quoted as of:', ctime())
print ('\nTICKER'.ljust(9), 'PRICE'.ljust(8), 'CHG'.ljust(5), '%AGE')
print ('------'.ljust(8), '-----'.ljust(8), '---'.ljust(5), '----')
u = urlopen(URL % ','.join(ticks))
for row in u:
tick, price, chg, per = row.split(',')
print(eval(tick).ljust(7),('%.2f' % round(float(price), 2)).rjust(6), chg.rjust(6),
eval(per.rstrip()).rjust(6))
f.close()
Output

You might also like