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

unit 4 python

This document provides an overview of network programming and GUI using Python, detailing key concepts such as Internet protocols (UDP and TCP), IP addresses, ports, and socket programming. It explains the differences between UDP and TCP, introduces socket methods for server and client communication, and demonstrates how to use libraries like urllib and requests for web scraping and file downloading. Additionally, it includes examples of creating simple TCP and UDP servers and clients in Python.

Uploaded by

Priyank Raychura
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

unit 4 python

This document provides an overview of network programming and GUI using Python, detailing key concepts such as Internet protocols (UDP and TCP), IP addresses, ports, and socket programming. It explains the differences between UDP and TCP, introduces socket methods for server and client communication, and demonstrates how to use libraries like urllib and requests for web scraping and file downloading. Additionally, it includes examples of creating simple TCP and UDP servers and clients in Python.

Uploaded by

Priyank Raychura
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT 4: NETWORK

PROGRAMMING AND GUI USING


PYTHON

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 1

Network Programming
Python plays an essential role in network programming. The standard library of Python has full
support for network protocols, encoding, and decoding of data and other networking concepts,
and it is simpler to write network programs in Python than that of C++.

Internet Protocol
These are the set of procedures or rules which govern the flow of data, format of data over the
internet. Mainly, we will be dealing with two major protocols over the internet:
• User Datagram Protocol(UDP)
• Transmission Control Protocol(TCP)

User Datagram Protocol (UDP)


UDP is a connectionless protocol. In this protocol data is sent over the internet as datagrams.
some properties of the UDP protocols.
• Unreliable: When a UDP message is sent, there is no way to know if it will reach its
destination or not; it could get lost along the way. In UDP, there is no concept of
acknowledgment, retransmission, or timeout (as in TCP).
• Not ordered: If two messages are sent to the same recipient, the order in which they
arrive cannot be predicted.
• Lightweight: There is no ordering of messages, no tracking connections, etc. Hence UDP
messages are used when the rate of data transmission required is more and relibility is not
important.
• Datagrams: Packets are sent individually and are checked for integrity only if they
arrive.

Transmission Control Protocol (TCP)


In TCP there is a concept of handshake. So, What is a handshake? It's a way to ensure that the
connection has been established between interested hosts and therefore data transfer can be
initiated
the properties of TCP:
• Reliable: TCP manages message acknowledgment, retransmission and timeout. Multiple
attempts to deliver the message are made. If it gets lost along the way, the server will re-
request the lost part.
• Ordered: The messages are delivered in a particular order in which they were meant to
be.
• Heavyweight: TCP requires three packets to set up a socket connection, before any user
data can be sent. The three packets are: SYN, SYN+ACK and ACK.

IP Addresses and Ports


IP addresses are the addresses which helps to uniquely identify a device over the internet and
Port is an endpoint for the communication in an operating system.
A system might be running thousands of services but to uniquely identify a service on a system
the application requires a port number. There are total of 0 – 65535 ports on a system.
Port numbers are sometimes seen in web or other uniform resource locators (URLs) as well. By
default, HTTP uses port 80 and HTTPS uses port 443
Some common ports are:
• 22: Secure Shell(SSH)
• 23: Telnet Remote Login Service

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 2

• 25: Simple Mail Transfer Protocol(SMTP)


• 53: Domain Name System(DNS) Service
• 80: Hyper Text Transfer Protocol(HTTP) used in the World Wide Web

Now, coming up is some more detail about the IP addressess. IP address is of two types:
1. Private IP address: Ranges from (192.168.0.0 – 192.168.255.255), (172.16.0.0 –
172.31.255.255) or (10.0.0.0 - 10.255.255.255)
2. Public IP address: A public IP address is an IP address that your home or business router
receives from your ISP(Internet Service Provider).

Python provides two levels of access to network programming. These are –


• Low-Level Access: At the low level, you can access the basic socket support of the
operating system. You can implement client and server for both connection-oriented and
connectionless protocols.
• High-Level Access: At the high level allows to implement protocols like HTTP, FTP,
etc.

What are Sockets?


Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate
within a process, between processes on the same machine, or between processes on different
continents.
Sockets may be implemented over a number of different channel types: Unix domain sockets,
TCP, UDP, and so on. The socket library provides specific classes for handling the common
transports as well as a generic interface for handling the rest.
Sockets have their own vocabulary −
Sr.No. Term & Description

1 Domain
The family of protocols that is used as the transport mechanism. These values are
constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.

2 type
The type of communications between the two endpoints, typically SOCK_STREAM for
connection-oriented protocols and SOCK_DGRAM for connectionless protocols.

3 protocol
Typically zero, this may be used to identify a variant of a protocol within a domain and
type.

4 hostname
The identifier of a network interface −
• A string, which can be a host name, a dotted-quad address, or an IPV6 address
in colon (and possibly dot) notation
• A string "<broadcast>", which specifies an INADDR_BROADCAST address.
• A zero-length string, which specifies INADDR_ANY, or
• An Integer, interpreted as a binary address in host byte order.

5 port
Each server listens for clients calling on one or more ports. A port may be a Fixnum

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 3

port number, a string containing a port number, or the name of a service.

Socket Programming
Socket programming is a way of connecting two nodes on a network to communicate with each
other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to
the other to form a connection. The server forms the listener socket while the client reaches out
to the server. They are the real backbones behind web browsing. In simpler terms, there is a
server and a client. We can use the socket module for socket programming. For this, we have to
include the socket module –
import socket
to create a socket we have to use the socket.socket() method.
Syntax:
socket.socket(socket_family, socket_type, protocol=0)
Where,
• socket_family: Either AF_UNIX or AF_INET
• socket_type: Either SOCK_STREAM or SOCK_DGRAM.
• protocol: Usually left out, defaulting to 0.

Example:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(s)
output
<socket.socket fd=732, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM,
proto=0>

Once you have socket object, then you can use required functions to create your client or server
program. Following is the list of functions required −

Server Socket Methods


Sr.No. Method & Description

1 s.bind()
This method binds address (hostname, port number pair) to socket.

2 s.listen()
This method sets up and start TCP listener.

3 s.accept()
This passively accept TCP client connection, waiting until connection arrives
(blocking).

Client Socket Methods


Sr.No. Method & Description

1 s.connect()

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 4

This method actively initiates TCP server connection.

General Socket Methods


Sr.No. Method & Description

1 s.recv()
This method receives TCP message

2 s.send()
This method transmits TCP message

3 s.recvfrom()
This method receives UDP message

4 s.sendto()
This method transmits UDP message

5 s.close()
This method closes socket

6 socket.gethostname()
Returns the hostname.

Knowing IP Address
An IP(Internet Protocol) address is an identifier assigned to each computer and other device(e.g.,
router, mobile, etc) connected to a TCP/IP network that is used to locate and identify the node in
communication with other nodes on the network. IP addresses are usually written and displayed
in human-readable notation such as 192.168.1.35 in IPv4(32-bit IP address).

Example
# Python Program to Get IP Address
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)

Reading the source code of a web page


To read the source code install following library
python -m pip install requests
Example
import requests
req = requests.get('http://python.org')
txt=req.text
txt=txt.split('\n')
for x in txt[:25]:
print(x)

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 5

What is urllib?
urllib is a Python module that can be used for opening URLs. It defines functions and classes to
help in URL actions.
With Python you can also access and retrieve data from the internet like XML, HTML, JSON,
etc. You can also use Python to work with this data directly. In this tutorial we are going to see
how we can retrieve data from the web.

How to Open URL using Urllib


Before we run the code to connect to Internet data, we need to import statement for URL library
module or “urllib”.
• Import urllib
• Declare the variable webUrl
• Then call the urlopen function on the URL lib library
• Next, print the result code
• Result code is retrieved by calling the getcode function on the webUrl variable we have
created
• Convert that to a string, so that it can be concatenated with our string “result code”
• This will be a regular HTTP code “200”, indicating http request is processed successfully.
• Read the HTML file by using the “read function” in Python, and when you run the code,
the HTML file will appear in the console.

Example
import urllib.request
webUrl = urllib.request.urlopen('https://christcollegerajkot.edu.in/Motto/')
print ("result code: " + str(webUrl.getcode()))
data = webUrl.read(1000)
print (data)

What is Beautiful Soup?


Beautiful Soup is a Python library that is used for web scraping purposes to pull the data out of
HTML and XML files. It creates a parse tree from page source code that can be used to extract
data in a hierarchical and more readable manner.

Installation
python -m pip install beautifulsoup4

Example
import urllib.request
from bs4 import BeautifulSoup
response = urllib.request.urlopen('file:///D://christ/kruti/sample.html')
html_doc = response.read()
# Parse the html file
soup = BeautifulSoup(html_doc, 'html.parser')
for x in soup.find_all('h1'):
print(x.string)

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 6

Downloading files from web using Python


Requests is a versatile HTTP library in python with various applications. One of its applications
is to download a file from web using the file URL.
Advantages of using Requests library to download web files are:
• One can easily download the web directories by iterating recursively through the website!
• This is a browser-independent method and much faster!

Downloading image
Example(png)
# imported the requests library
import requests
image_url = "https://www.python.org/static/community_logos/python-logo-master-v3-TM.png"

# URL of the image to be downloaded is defined as image_url


r = requests.get(image_url) # create HTTP response object

# send a HTTP request to the server and save


# the HTTP response in a response object called r
with open("python_logo.png",'wb') as f:

# Saving received content as a png file in


# binary format

# write the contents of the response (r.content)


# to a new file in binary mode.
f.write(r.content)

This small piece of code written above will download the following image from the web. Now
check your local directory(the folder where this script resides), and you will find this image:
All we need is the URL of the image source. (You can get the URL of image source by right-
clicking on the image and selecting the View Image option.)

Download pdf/large files


The HTTP response content (r.content) is nothing but a string which is storing the file data. So,
it won’t be possible to save all the data in a single string in case of large files. To overcome this
problem, we do some changes to our program:
Since all file data can’t be stored by a single string, we use r.iter_content method to load data in
chunks, specifying the chunk size.
r = requests.get(URL, stream = True)
Setting stream parameter to True will cause the download of response headers only and the
connection remains open. This avoids reading the content all at once into memory for large
responses. A fixed chunk will be loaded each time while r.iter_content is iterated.

Example
import requests
file_url =
"http://www.halvorsen.blog/documents/programming/python/resources/Python%20Programming
.pdf"

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 7

r = requests.get(file_url, stream = True)


with open("python.pdf","wb") as pdf:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
pdf.write(chunk)

Downloading web page


Example
import urllib.request, urllib.error, urllib.parse
url='https://christcollegerajkot.edu.in/Objectives/'
response = urllib.request.urlopen(url)
webContent = response.read().decode('UTF-8')
f = open('demo1.html', 'w')
f.write(webContent)
f.close

A Simple TCP Server


To write Internet servers, we use the socket function available in socket module to create a
socket object. A socket object is then used to call other functions to setup a socket server.
Now call bind(hostname, port) function to specify a port for your service on the given host.
Next, call the accept method of the returned object. This method waits until a client connects to
the port you specified, and then returns a connection object that represents the connection to that
client.

Example: tcp_server.py
import socket #line 1: Import socket module
s = socket.socket() #line 2: create a socket object
host = socket.gethostname() #line 3: Get current machine name
port = 9999 #line 4: Get port number for connection
s.bind((host,port)) #line 5: bind with the address
print ("Waiting for connection...")
s.listen(5) #line 6: listen for connections
msg="saying hi"
while True:
conn,addr = s.accept() #line 7: connect and accept from client
print ('Got Connection from', addr)
conn.send(b"saying hi")
conn.close() #line 8: Close the connection

A Simple TCP Client


Let us write a very simple client program which opens a connection to a given port 12345 and
given host. This is very simple to create a socket client using Python's socket module function.
The socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once
you have a socket open, you can read from it like any IO object. When done, remember to close
it, as you would close a file.
The following code is a very simple client that connects to a given host and port, reads any
available data from the socket, and then exits −

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 8

Example: tcp_client.py
import socket
s = socket.socket()
host = socket.gethostname() # Get current machine name
port = 9999 # Client wants to connect to server's
# port number 9999
s.connect((host,port))
print (s.recv(1024)) # 1024 is bufsize or max amount
# of data to be received at once
s.close()

Now open terminal (cmd) and run the server script from the location you have saved the script:
C:\Users\programs> py tcp_server.py

Now open a new terminal (cmd) and run the client script from the location you have saved the
script:
C\Users\programs>py tcp_client.py

A UDP Server

Example: udpserver.py
import socket
localIP = "127.0.0.1"
localPort = 20001
bufferSize = 1024
msgFromServer = "Hello UDP Client"
bytesToSend = str.encode(msgFromServer)
# Create a datagram socket
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Bind to address and ip
UDPServerSocket.bind((localIP, localPort))

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 9

print("UDP server up and listening")


# Listen for incoming datagrams

while(True):
bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
clientMsg = "Message from Client:{}".format(message)
clientIP = "Client IP Address:{}".format(address)
print(clientMsg)
print(clientIP)
# Sending a reply to client
UDPServerSocket.sendto(bytesToSend, address)

Example: udpclient.py
import socket
msgFromClient = "Hello UDP Server"
bytesToSend = str.encode(msgFromClient)
serverAddressPort = ("127.0.0.1", 20001)
bufferSize = 1024
# Create a UDP socket at client side
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Send to server using created UDP socket
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
msgFromServer = UDPClientSocket.recvfrom(bufferSize)
msg = "Message from Server {}".format(msgFromServer[0])
print(msg)

File Server
Setup A Basic File server Using simpleHTTPserver:
Just run the following command from your Terminal to start the file server:
$ python -m http.server 8000

Sample output would be:


Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ..

That's it. File server is ready. Open the web browser and type:
localhost:8000/

Here it is how my local server's contents looks in my browser:

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 10

Two-way communication between server and client


A server is a software that waits for client requests and serves or processes them accordingly.
On the other hand, a client is requester of this service. A client program request for some
resources to the server and server responds to that request.
Socket is the endpoint of a bidirectional communications channel between server and client.
Sockets may communicate within a process, between processes on the same machine, or between
processes on different machines. For any communication with a remote program, we have to
connect through a socket port.

We will design both server and client model so that each can communicate with them. The steps
can be considered like this.
1. Python socket server program executes at first and wait for any request
2. Python socket client program will initiate the conversation at first.
3. Then server program will response accordingly to client requests.
4. Client program will terminate if user enters “bye” message. Server program will also
terminate when client program terminates, this is optional and we can keep server
program running indefinitely or terminate with some specific command in client request.

Python Socket Server


We will save python socket server program as socket_server.py. To use python socket
connection, we need to import socket module.
Then, sequentially we need to perform some tasks to establish connection between server and
client.
We can obtain host address by using socket.gethostname() function. It is recommended to user
port address above 1024 because port number lesser than 1024 are reserved for standard internet
protocol.

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 11

Example: socket_server.py
import socket
def server_program():
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024

server_socket = socket.socket() # get instance


# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together

# configure how many client the server can listen simultaneously


server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
while True:
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if not data:
# if data is not received break
break
print("from connected user: " + str(data))
data = input(' -> ')
conn.send(data.encode()) # send data to the client

conn.close() # close the connection

server_program()

So our python socket server is running on port 5000 and it will wait for client request. If you
want server to not quit when client connection is closed, just remove the if condition and break
statement. Python while loop is used to run the server program indefinitely and keep waiting for
client request.

Python Socket Client


We will save python socket client program as socket_client.py. This program is similar to the
server program, except binding.
The main difference between server and client program is, in server program, it needs to bind
host address and port address together.

Example:socket_client.py
import socket
def client_program():
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number

client_socket = socket.socket() # instantiate


client_socket.connect((host, port)) # connect to the server

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 12

message = input(" -> ") # take input

while message.lower().strip() != 'bye':


client_socket.send(message.encode()) # send message
data = client_socket.recv(1024).decode() # receive response
print('Received from server: ' + data) # show in terminal
message = input(" -> ") # again take input
client_socket.close() # close the connection

client_program()

Python Socket Programming Output


To see the output, first run the socket server program in cmd. Then open new cmd and run the
socket client program. After that, write something from client program. Then again write reply
from server program. At last, write bye from client program to terminate both program

Sending simple mail using Python


Sending Email using SMTP
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing
e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can be used
to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail −
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Here is the detail of the parameters −
• host − This is the host running your SMTP server. You can specify IP address of the host
or a domain name like tutorialspoint.com. This is optional argument.
• port − If you are providing host argument, then you need to specify a port, where SMTP
server is listening. Usually this port would be 1025.
• local_hostname − If your SMTP server is running on your local machine, then you can
specify just localhost as of this option.
An SMTP object has an instance method called sendmail, which is typically used to do the work
of mailing a message. It takes three parameters −
• The sender − A string with the address of the sender.
• The receivers − A list of strings, one for each recipient.
• The message − A message as a string formatted as specified in the various RFCs.

You can test email functionality by running a local SMTP debugging server, using
the smtpd module that comes pre-installed with Python. Rather than sending emails to the
specified address, it discards them and prints their content to the console. Running a local
debugging server means it’s not necessary to deal with encryption of messages or use credentials
to log in to an email server.
You can start a local SMTP debugging server by typing the following in Command Prompt:
python -m smtpd -c DebuggingServer -n localhost:1025
Any emails sent through this server will be discarded and shown in the terminal window as
a bytes object for each line.

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 13

Example
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
message = """From: From Kruti <[email protected]>
To: To Tosha <[email protected]>
Subject: SMTP e-mail test

This is a test e-mail message.


"""
try:
smtpObj = smtplib.SMTP('localhost',1025)
smtpObj.sendmail(sender, receivers, message)
print ("Successfully sent email")
except SMTPException:
print ("Error: unable to send email")

Output:
On Python Shell :
Successfully sent email

On CMD:
---------- MESSAGE FOLLOWS ----------
b'From: From Kruti <[email protected]>'
b'To: To Tosha <[email protected]>'
b'Subject: SMTP e-mail test'
b'X-Peer: ::1'
b''
b'This is a test e-mail message.'
------------ END MESSAGE ------------

Send mail from your Gmail account using Python


To set up a Gmail address for testing your code, do the following:
• Create a new Google account.
• Go to manage your google account -> security -> Less Secure app access
• Turn Allow less secure apps to ON. Be aware that this makes it easier for others to gain
access to your account.

“smtplib” creates a Simple Mail Transfer Protocol client session object which is used to send
emails to any valid email id on the internet. Different websites use different port numbers.
We are using a Gmail account to send a mail. Port number used here is ‘587’. And if you want to
send mail using a website other than Gmail, you need to get the corresponding information.
Steps to send mail from Gmail account:
1. First of all, “smtplib” library needs to be imported.
2. After that, to create a session, we will be using its instance SMTP to encapsulate an
SMTP connection.
s = smtplib.SMTP('smtp.gmail.com', 587)

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 14

In this, you need to pass the first parameter of the server location and the second parameter of the
port to use. For Gmail, we use port number 587.
3. For security reasons, now put the SMTP connection in the TLS mode. TLS (Transport
Layer Security) encrypts all the SMTP commands. After that, for security and
authentication, you need to pass your Gmail account credentials in the login instance.The
compiler will show an authentication error if you enter invalid email id or password.
4. Store the message you need to send in a variable say, message. Using the sendmail()
instance, send your message. sendmail() uses three parameters: sender_email_id,
receiver_email_id and message_to_be_sent. The parameters need to be in the same
sequence.
This will send the email from your account. After you have completed your task, terminate the
SMTP session by using quit().

Example
# Python code to illustrate Sending mail from your Gmail account
import smtplib

# creates SMTP session


s = smtplib.SMTP('smtp.gmail.com', 587)

# start TLS for security


s.starttls()

# Authentication
s.login("sender_email_id", "sender_email_id_password")

# message to be sent
message = "Message_you_need_to_send"

# sending the mail


s.sendmail("sender_email_id", "receiver_email_id", message)

# terminating the session


s.quit()

GUI Programming
A graphical user interface (GUI) allows a user to interact with a computer program using a
pointing device that manipulates small pictures on a computer screen. The small pictures are
called icons or widgets. Various types of pointing devices can be used, such as a mouse, a stylus
pen, or a human finger on a touch screen.

Event-driven programming paradigm


A GUI program creates the icons and widgets that are displayed to a user and then it simply waits
for the user to interact with them. The order that tasks are performed by the program is under the
user’s control – not the program’s control! This means a GUI program must keep track of the
“state” of its processing and respond correctly to user commands that are given in any order the
user chooses. This style of programming is called “event driven programming.” In fact, by
definition, all GUI programs are event-driven programs.

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 15

Creating simple GUI


GUI program has the following structure:
• Create the icons and widgets that are displayed to a user and organize them inside a
screen window.
• Define functions that will process user and application events.
• Associate specific user events with specific functions.
• Start an infinite event-loop that processes user events. When a user event happens, the
event-loop calls the function associated with that event.

GUI Programming options:


Python does not implement GUI, event-driven-programming in its core functionality. GUI
programming is implemented using imported modules which are often referred to as “toolkits.”
Anyone can implement external modules that facilitate GUI programming, and many people
have. Therefore, you have many options available to you for GUI programming.
Python provides several different options for writing GUI based programs. These 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.
There are many other interfaces available for GUI. But these are the most commonly used ones.

Python GUI – tkinter


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:
1. Importing the module – tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. 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’.
import tkinter

There are two main methods used which the user needs to remember while creating the Python
application with GUI.
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:
m=tkinter.Tk() #where m is the name of the main window object
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.

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 16

m.mainloop()

Example:
import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()

Geometry Management (Layouts)


tkinter also offers access to the geometric configuration of the widgets which can organize the
widgets in the parent windows. There are mainly three geometry manager classes class.
1. pack() method:It organizes the widgets in blocks before placing in the parent widget.
2. grid() method:It organizes the widgets in grid (table-like structure) before placing in the
parent widget.
3. place() method:It organizes the widgets by placing them on specific positions directed
by the programmer.

Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets. There are a number of widgets which
you can put in your tkinter application.

Sr.No. Operator & Description

1 Button
The Button widget is used to display buttons in your application.

2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and
rectangles, in your application.

3 Checkbutton
The Checkbutton widget is used to display a number of options as checkboxes. The user
can select multiple options at a time.

4 Entry
The Entry widget is used to display a single-line text field for accepting values from a
user.

5 Frame
The Frame widget is used as a container widget to organize other widgets.

6 Label
The Label widget is used to provide a single-line caption for other widgets. It can also
contain images.

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 17

7 Listbox
The Listbox widget is used to provide a list of options to a user.

8 Menubutton
The Menubutton widget is used to display menus in your application.

9 Menu
The Menu widget is used to provide various commands to a user. These commands are
contained inside Menubutton.

10 Message
The Message widget is used to display multiline text fields for accepting values from a
user.

11 Radiobutton
The Radiobutton widget is used to display a number of options as radio buttons. The
user can select only one option at a time.

12 Scale
The Scale widget is used to provide a slider widget.

13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various widgets, such as list
boxes.

14 Text
The Text widget is used to display text in multiple lines.

15 Toplevel
The Toplevel widget is used to provide a separate window container.

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

17 PanedWindow
A PanedWindow is a container widget that may contain any number of panes, arranged
horizontally or vertically.

18 LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer or
container for complex window layouts.

19 tkMessageBox
This module is used to display message boxes in your applications.

Some of the major widgets are explained below:

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 18

Button
To add a button in your application, this widget is used.
The general syntax is:
w=Button(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the Buttons. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• activebackground: to set the background color when button is under the cursor.
• activeforeground: to set the foreground color when button is under the cursor.
• 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

Example
import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()

Label
It refers to the display box where you can put any text or image which can be updated any time
as per the code.
The general syntax is:
w=Label(master, option=value)
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. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• bg: to set the 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.

Example
from tkinter import *
root = Tk()
w = Label(root, text='This is label',bg="red",height=20,width=30)
w.pack()
root.mainloop()

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 19

Entry
It is used to input the single line text entry from the user.. For multi-line text input, Text widget is
used.
The general syntax is:
w=Entry(master, option=value)
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. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• command: to call a function.
• highlightcolor: to set the color shown in the focus highlight.
• width: to set the width of the button.
• height: to set the height of the button.

Example
from tkinter import *
master = Tk()
Label(master, text='First Name').grid(row=0,column=0)
Label(master, text='Last Name').grid(row=0,column=2)
e1 = Entry(master,bd=5)
e2 = Entry(master,bg="pink")
e1.grid(row=0, column=1)
e2.grid(row=0, column=3)

#another layout(two text boxes in two rows)


'''Label(master, text='First Name').grid(row=0)
Label(master, text='Last Name').grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)'''

mainloop()

Frame
It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The
general syntax is:
w = Frame(master, option=value)
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. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• highlightcolor: To set the color of the focus highlight when widget has to be focused.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• width: to set the width of the widget.
• height: to set the height of the widget.

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 20

Example
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()

Tkinter Standard Dialog Boxes


There are many common programming tasks that can be performed using pre-defined GUI dialog
boxes.

Messagebox
The message dialogues are provided by the 'messagebox' submodule of tkinter.
'messagebox' consists of the following functions, which correspond to dialog windows:
• askokcancel(title=None, message=None, **options)
Ask if operation should proceed; return true if the answer is ok
• askquestion(title=None, message=None, **options)
Ask a question
• askretrycancel(title=None, message=None, **options)
Ask if operation should be retried; return true if the answer is yes
• askyesno(title=None, message=None, **options)
Ask a question; return true if the answer is yes
• askyesnocancel(title=None, message=None, **options)
Ask a question; return true if the answer is yes, None if cancelled.
• showerror(title=None, message=None, **options)
Show an error message
• showinfo(title=None, message=None, **options)
Show an info message
• showwarning(title=None, message=None, **options)
Show a warning message

Showing only message in a box


A messagebox can display information to a user. There are three variations on these dialog boxes
based on the type of message you want to display. The functions’ first parameter gives a name
for the dialog box which is displayed in the window’s header. The second parameter is the text of
the message. The functions return a string which is typically ignored.

Example
from tkinter import messagebox

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 21

messagebox.showinfo("Information","Informative message")
messagebox.showerror("Error", "Error message")
messagebox.showwarning("Warning","Warning message")

Yes/No Questions
The tkinter messagebox object also allows you to ask a user simple yes/no type questions and
varies the button names based on the type of question. These functions are:

Example
from tkinter import messagebox
answer = messagebox.askokcancel("Question","Do you want to open this file?")
print(answer)
answer = messagebox.askretrycancel("Question", "Do you want to try that again?")
print(answer)
answer = messagebox.askyesno("Question","Do you like Python?")
print(answer)
answer = messagebox.askyesnocancel("Question", "Continue playing?")
print(answer)
The return value is a Boolean, True or False, answer to the question. If “cancel” is an option and
the user selects the “cancel” button, None is returned.

Single Value Data Entry


If you want to ask the user for a single data value, either a string, integer, or floating point value,
you can use a simpledialog object. A user can enter the requested value and hit “OK”, which will
return the entered value. If the user hits “Cancel,” then None is returned.

Example
import tkinter as tk
from tkinter import simpledialog

application_window = tk.Tk()

answer = simpledialog.askstring("Input", "What is your first name?",


parent=application_window)
if answer is not None:
print("Your first name is ", answer)
else:
print("You don't have a first name?")

answer = simpledialog.askinteger("Input", "What is your age?",


parent=application_window,
minvalue=0, maxvalue=100)
if answer is not None:
print("Your age is ", answer)
else:
print("You don't have an age?")

answer = simpledialog.askfloat("Input", "What is your salary?",


parent=application_window,

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 22

minvalue=0.0, maxvalue=100000.0)
if answer is not None:
print("Your salary is ", answer)
else:
print("You don't have a salary?")

File Chooser
A common task is to select the names of folders and files on a storage device. This can be
accomplished using a filedialog object. Note that these commands do not save or load a file.
They simply allow a user to select a file. Once you have the file name, you can open, process,
and close the file using appropriate Python code. These dialog boxes always return you a “fully
qualified file name” that includes a full path to the file. Also note that if a user is allowed to
select multiple files, the return value is a tuple that contains all of the selected files. If a user
cancels the dialog box, the returned value is an empty string.
Example
import tkinter as tk
from tkinter import filedialog
import os

application_window = tk.Tk()

# Build a list of tuples for each file type the file dialog should display
my_filetypes = [('all files', '.*'), ('text files', '.txt')]

# Ask the user to select a folder.


answer = filedialog.askdirectory(parent=application_window,
initialdir=os.getcwd(),
title="Please select a folder:")
print(answer)

# Ask the user to select a single file name.


answer = filedialog.askopenfilename(parent=application_window,
initialdir=os.getcwd(),
title="Please select a file:",
filetypes=my_filetypes)
print(answer)

# Ask the user to select a one or more file names.


answer = filedialog.askopenfilenames(parent=application_window,
initialdir=os.getcwd(),
title="Please select one or more files:",
filetypes=my_filetypes)
print(answer)

# Ask the user to select a single file name for saving.


answer = filedialog.asksaveasfilename(parent=application_window,
initialdir=os.getcwd(),
title="Please select a file name for saving:",
filetypes=my_filetypes)

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 23

print(answer)

Color Chooser
Tkinter includes a nice dialog box for choosing colors. You provide it with a parent window and
an initial color, and it returns a color in two different specifications: 1) a RGB value as a tuple,
such as (255, 0, 0) which represents red, and 2) a hexadecimal string used in web pages, such
as "#FF0000" which also represents red. If the user cancels the operation, the return values
are None and None.

Example
import tkinter as tk
from tkinter.colorchooser import askcolor

def callback():
result = askcolor(color="#6A9662",
title = "Bernd's Colour Chooser")
print(result)

root = tk.Tk()
tk.Button(root,
text='Choose Color',
fg="darkgreen",
command=callback).pack(side=tk.LEFT, padx=10)
tk.Button(text='Quit',
command=root.quit,
fg="red").pack(side=tk.LEFT, padx=10)
tk.mainloop()

Compiled by: Kruti Kotak, Christ College, Rajkot

You might also like