0% found this document useful (0 votes)
3 views32 pages

Python Unit - 4

The document provides an overview of network programming and GUI using Python, focusing on socket programming, including both TCP and UDP protocols. It includes examples of server and client programs, methods for sending and receiving messages, and instructions for setting up a file server and sending emails using SMTP. Additionally, it covers how to retrieve and download web pages and images from the internet using Python.

Uploaded by

vishwasgroup
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)
3 views32 pages

Python Unit - 4

The document provides an overview of network programming and GUI using Python, focusing on socket programming, including both TCP and UDP protocols. It includes examples of server and client programs, methods for sending and receiving messages, and instructions for setting up a file server and sending emails using SMTP. Additionally, it covers how to retrieve and download web pages and images from the internet using Python.

Uploaded by

vishwasgroup
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

Network Programming and GUI using Python

Network Programming
 Protocol & Sockets :

Python provides two levels of access to network services. At a low level, we can
access the basic socket support in the underlying operating system, which allows
you to implement clients and servers for both connection-oriented and
connectionless protocols.
 What is 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.

 SOCKET terms and Description :

TERMS DESCRIPTION

 The family of protocols that is used as the transport mechanism.


Domain  These values are constants such as AF_INET, PF_INET, PF_UNIX,
PF_X25, and so on.
 The type of communications between the two endpoints, typically
type SOCK_STREAM for connection-oriented protocols and
SOCK_DGRAM for connectionless protocols.
 Typically zero, this may be used to identify a variant of a protocol
protocol within a domain and type.
This is 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
Hostname  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.
 Each server listens for clients calling on one or more ports. A port
port may be a Fixnum port number, a string containing a port number,
or the name of a service.

Python Notes By : Hiral Pandya Page : 1 of 32


 Server Socket Methods :

METHODS DESCRIPTION

[Link]() This method binds address (hostname, port number pair) to socket.

[Link]() This method sets up and start TCP listener.

This passively accept TCP client connection, waiting until connection


[Link]()
arrives (blocking).

 Client Socket Methods :

METHODS DESCRIPTION

[Link]() This method actively initiates TCP server connection.

 General Socket Methods :

METHODS DESCRIPTION

[Link]() This method receives TCP message

[Link]() This method transmits TCP message

[Link]() This method receives UDP message

[Link]() This method transmits UDP message

[Link]() This method closes socket

[Link]() Returns the hostname.

Python Notes By : Hiral Pandya Page : 2 of 32


 Simple Server Program:

Save the file with filename : [Link].


import socket
T_PORT = 60
TCP_IP = '[Link]'
BUF_SIZE = 30
# create a socket object name 's'
s = [Link] (socket.AF_INET, socket.SOCK_STREAM)
[Link]((TCP_IP, T_PORT))
[Link](1)
con, addr = [Link]()
print ('Connection Address is: ' , addr)
while True :
data = [Link](BUF_SIZE)
if not data:
break
print ("Received data", data)
[Link](data)
[Link]()
This will open a web server at port 60 and everything written in the client will
be gone to the server.
 Simple Client Program:
import socket
T_PORT = 5006
TCP_IP = '[Link]'
BUF_SIZE = 1024
MSG = "Hello HJD"
# create a socket object name 's'
s = [Link] (socket.AF_INET, socket.SOCK_STREAM)
[Link]((TCP_IP, T_PORT))
[Link](MSG)
data = [Link](BUF_SIZE)
[Link]

Python Notes By : Hiral Pandya Page : 3 of 32


 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 [Link] in IPv4 (32-bit IP address).

 IP Address Program:

#importing socket module


import socket
#getting the hostname by [Link]() method
hostname = [Link]()
#getting the IP address using [Link]() method
ip_address = [Link](hostname)
#printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")

 Reading the Source Code of a Web Page :


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

from urllib import request


import requests
url = "[Link]
html_output_name = "[Link]"
print("Page is Downloading...")
req = [Link](url, '[Link]')
print("-"*40)
with open(html_output_name, 'w') as f:
[Link]([Link])
[Link]()
print("-"*40)
print("Page Content is Downloaded in [Link]...")
print("-"*40)

Python Notes By : Hiral Pandya Page : 4 of 32


 Downloading a Web Page / Image from Internet :
A web page is a file that is stored on another computer, a machine known as a
web server. When we visit a web page, what is actually happening is that our
computer, (the client) sends a request to the server (the host) out over the
network and the server replies by sending a copy of the page back to our
machine. One way to get to a web page with your browser is to follow a link
from somewhere else. You also have the ability, of course, to paste or type a
Uniform Resource Locator (URL) directly into your browser. The URL tells our
browser where to find an online resource by specifying the server, directory
and name of the file to be retrieved, as well as the kind of protocol that the
server and your browser will agree to use while exchanging information.

import requests

image_url = "[Link]
print("WebPage/Image is Downloading....")
# URL of the image to be downloaded is defined as image_url
r = [Link](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("[Link]",'wb') as f:
# Saving received content as a png file in
# binary format
# write the contents of the response ([Link])
# to a new file in binary mode.
[Link]([Link])
print("="*30)
print("WebPage Image is Downloaded")
print("="*30)

 A TCP/IP Server & Client:


TCP/IP specifies how data is exchanged over the internet by providing
end-to-end communications that identify how it should be broken into packets,
addressed, transmitted, routed and received at the destination.
Python Notes By : Hiral Pandya Page : 5 of 32
 TCP defines how applications can create channels of communication across a
network. It also manages how a message is assembled into smaller packets
before they are then transmitted over the internet and reassembled in the right
order at the destination address.
 IP defines how to address and route each packet to make sure it reaches the
right destination. Each gateway computer on the network checks this IP
address to determine where to forward the message.

TCP/IP Server Side Code : [Link]


import socket
# Standard loopback interface address (localhost)
HOST = "[Link]"
# Port to listen on (non-privileged ports are > 1023)
PORT = 65432

print("Connecting....")
with [Link](socket.AF_INET, socket.SOCK_STREAM) as
s:
[Link]((HOST, PORT))
[Link]()
conn, addr = [Link]()
with conn:
print(f"Connected by {addr}")
while True:
data = [Link](1024)
if not data:
break
[Link](data)
print("Data is Collecting....")

TCP/IP Client Side Code : [Link]


import socket
# The server's hostname or IP address
HOST = "[Link]"
# The port used by the server
PORT = 65432
print("Connecting To Server....")
with [Link](socket.AF_INET, socket.SOCK_STREAM) as s:
[Link]((HOST, PORT))
[Link](b"Hello, world")
data = [Link](1024)
print(f"Received {data!r}")

Python Notes By : Hiral Pandya Page : 6 of 32


 A UDP Server & Client:
UDP is the abbreviation of User Datagram Protocol. UDP makes use of Internet
Protocol of the TCP/IP suit. In communications using UDP, a client program
sends a message packet to a destination server wherein the destination server
also runs on UDP.

 Properties of UDP:
 The UDP does not provide guaranteed delivery of message packets. If for
some issue in a network if a packet is lost it could be lost forever.
 Since there is no guarantee of assured delivery of messages, UDP is
considered an unreliable protocol.
 The underlying mechanisms that implement UDP involve no connection-
based communication. There is no streaming of data between a UDP server
or and an UDP Client.
 An UDP client can send "n" number of distinct packets to an UDP server and
it could also receive "n" number of distinct packets as replies from the UDP
server.
 Since UDP is connectionless protocol the overhead involved in UDP is less
compared to a connection based protocol like TCP.

Python Notes By : Hiral Pandya Page : 7 of 32


UDP Server Side Code: [Link]

import socket
localIP = "[Link]"
localPort = 20001
bufferSize = 1024
msgFromServer = "Hello UDP Client"
bytesToSend = [Link](msgFromServer)

# Create a datagram socket

UDPServerSocket = [Link](family=socket.AF_INET,
type=socket.SOCK_DGRAM)

# Bind to address and ip

[Link]((localIP, localPort))

print("UDP server up and listening")

# Listen for incoming datagrams

while(True):

bytesAddressPair =
[Link](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

[Link](bytesToSend, address)

Python Notes By : Hiral Pandya Page : 8 of 32


UDP Client Side Code: [Link]
import socket
msgFromClient= "Hello UDP Server"
bytesToSend = [Link](msgFromClient)

serverAddressPort = ("[Link]", 20001)

bufferSize = 1024

# Create a UDP socket at client side

UDPClientSocket = [Link](family=socket.AF_INET,
type=socket.SOCK_DGRAM)

# Send to server using created UDP socket

[Link](bytesToSend, serverAddressPort)

msgFromServer = [Link](bufferSize)

msg = "Message from Server {}".format(msgFromServer[0])

print(msg)

 File Server :
 A file server is a computer responsible for the storage and management of
data files so that other computers on the same network can access the files.
It enables users to share information over a network without having to
physically transfer files. A simpleHTTPserver is a python module that can be
used to setup a file server or serve a directory instantly in network. Anyone
in the network can instantly access the folder or files from your system.
 Python has a built-in web server provided by its standard library, can be
called for simple client-server communication. The [Link] and
socketserver are the two main functions used to create a server. Port
number can be defined manually in the program which is used to access the
web server.

Python Notes By : Hiral Pandya Page : 9 of 32


 How do file servers work?
o File servers only make a remote file system accessible to clients. They can
store any type of data -- for example, executables, documents, photos or
videos.
o They generally store the data as blobs of binary data or files. This means
that they don't perform additional indexing or processing of the files stored
on them. There may be additional plugins or server functions that can
provide extra features, however.
o A file server does not provide built-in ways to interact with the data and
relies on the client to use it. Databases are not considered file servers
because databases only deal with structured data that is accessed by a
query.
 How To Start file servers?
o Start Command Prompt.
o Write Command “python -m [Link] 8000”. This will start File Server.
o Write Command “python -m [Link] –bind [Link] 8000”. This will
start File Server on Given TCP.
o Enter “localhost:8000 ” in web browser.
o To Stop File Server, Press “Ctrl+C” on Command Prompt
 File Client :
o A file client is a computer responsible for access data files. It enables users
to access information over a network without having to physically transfer
files.

Python Notes By : Hiral Pandya Page : 10 of 32


File Server Code : [Link]

import [Link]
import socketserver
PORT = 8000
handler = [Link]
print("."*40)
print("File Server Is Starting...")
print("."*40)
with [Link](("", PORT), handler) as httpd:
print("-"*40)
print("Server started at localhost:" + str(PORT))
httpd.serve_forever()

 Sending a Simple Mail :


 Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending
EMail and routing EMail 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.
 An SMTP object has an instance method called sendmail(), which is
typically used to do the work of mailing a message.
Parameters of SMTP object.
Parameter
Description
Name
This is the host running SMTP server. Just specify IP
address of the host OR a domain name like
host
“[Link]”
This is optional argument.
If host argument is provided, then its need to be
port specify a port, where SMTP server is listening.
Usually this port would be 25.
If SMTP server is running on local machine, then just
local_hostname
specify localhost as of this option

Python Notes By : Hiral Pandya Page : 11 of 32


Parameters of sendmail()method.

Parameter
Description
Name
sender It is a string with the address of the sender.
receivers It is list of strings, one for each recipient.

If is message as a string formatted as specified in the


message
various RFCs

Sending a E-Mail : [Link]

import smtplib
sender = 'from@[Link]'
receivers = ['to@[Link]']
message = """From: From Person <from@[Link]>
To: To Person <to@[Link]>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = [Link]('localhost')
[Link](sender, receivers, message)
print ("Successfully sent email")
except SMTPException:
print ("Error: unable to send email")

Python Notes By : Hiral Pandya Page : 12 of 32


Network Programming and GUI using Python
GUI Programming
 Event-driven programming paradigm :

Event-driven programming focuses on events. The flow of program depends upon


events. Lower Level Programming Languages dealing with either sequential or
parallel execution model but the model having the concept of event-driven
programming is called ASYNCHRONOUS MODEL. Event-driven programming
depends upon an event loop that is always listening for the new incoming events.
The working of event-driven programming is dependent upon events. Once an
event loops, then events decide what to execute and in what order. ASYNCIO
module was added in Python3 or higher and it provides infrastructure for writing
single-threaded concurrent code using co-routines.

Methods Of ASYNCIO Module

Methods Description

This method will provide the event


loop = get_event_loop()
loop for the current context.
This method arranges for the callback
loop.call_later
that is to be called after the given
(time_delay,callback,argument)
time_delay seconds.
This method arranges for a callback
that is to be called as soon as possible.
loop.call_soon
The callback is called after
(callback,argument)
call_soon() returns and when the
control returns to the event loop.
This method is used to return the
[Link]() current time according to the event
loop’s internal clock.
This method will set the event loop for
asyncio.set_event_loop()
the current context to the loop.
This method will create and return a
asyncio.new_event_loop()
new event loop object.
This method will run until stop()
loop.run_forever()
method is called.

Python Notes By : Hiral Pandya Page : 13 of 32


Example of event loop helps in printing “Hello HJD” by using the
get_event_loop() method

import asyncio

def hello_world(loop):

print('Hello HJD')

[Link]()

loop = asyncio.get_event_loop()

loop.call_soon(hello_world, loop)

loop.run_forever()

[Link]()

 Creating simple GUI :

Python is a very popular programming language thanks to its great degree of


readability, widespread adoption and most importantly, its beginner friendliness.
While being incredibly useful for the fields of data science and machine learning,
Python is also great for developing graphical user interfaces! In fact, it has many
frameworks that even beginners can use to easily get started with developing a
GUI.
Python provides various options for developing GRAPHICAL USER INTERFACES (GUIs).

Some important GUI Tools are as below:

 Tkinter : It is the Python interface to the Tk GUI toolkit shipped with Python.

 wxPython : It is an open-source Python interface for wxWindows.

 JPython : Itis a Python port for Java which gives Python scripts seamless
access to Java class libraries on the local machine.

Python Notes By : Hiral Pandya Page : 14 of 32


 Basic Widgets(Controls) To Develop GUIs :
 Button :
The Button widget is used to add buttons in a Python application. These
buttons can display text or images that convey the purpose of the buttons. A
function or a method can be attached to a button which is called automatically
when button is clicked.

Common Properties
Properties Description
activebackground Background color when the button is under the cursor
activeforeground Foreground color when the button is under the cursor.
bd Border width in pixels. Default is 2.
bg Normal background color.
Function or method to be called when the button is
command
clicked.
fg Normal foreground (text) color.
font Text font to be used for the button's label.
Height of the button in text lines (for textual buttons) or
height
pixels (for images).
The color of the focus highlight when the widget has
highlightcolor
focus.
image Image to be displayed on the button (instead of text).
How to show multiple text lines: LEFT to left-justify each
justify
line; CENTER to center them; or RIGHT to right-justify.
padx Additional padding left and right of the text.
pady Additional padding above and below the text.
Relief specifies the type of the border. Some of the values
relief
are SUNKEN, RAISED, GROOVE, and RIDGE.
Set this option to DISABLED to gray out the button and
state make it unresponsive. Has the value ACTIVE when the
mouse is over it. Default is NORMAL.
Default is -1, meaning that no character of the text on the
underline button will be underlined. If nonnegative, the
corresponding text character will be underlined
Width of the button in letters (if displaying text) or pixels
width
(if displaying an image).
If this value is set to a positive number, the text lines will
wraplength
be wrapped to fit within this length.

Python Notes By : Hiral Pandya Page : 15 of 32


Common Methods
Properties Description
Causes the button to flash several times between active
flash() and normal colors. Leaves the button in the state it was in
originally. Ignored if the button is disabled
Calls the button's callback, and returns what that function
invoke() returns. Has no effect if the button is disabled or there is
no callback.

Example : Simple Button


from tkinter import *
from tkinter import messagebox
top = Tk()
[Link]("200x200")
def helloCallBack():
msg = [Link]( "HJD Python", "Hello HJD")
Btn = Button(top, text = "Click Me", command = helloCallBack)
[Link](x = 70,y = 70)
[Link]()

Example : Formatted Button


from tkinter import *
from tkinter import messagebox
import [Link] as font
top = Tk()
[Link]("200x200")
myFont = [Link](family='Cambria',size=16,weight="bold")
def helloCallBack():
msg = [Link]( "HJD Python", "Hello HJD")
btn = Button(top, text = "Click Me",bg='Navy', fg='White',
command = helloCallBack)
btn['font'] = myFont
[Link](x = 50,y = 50)
[Link]()

Python Notes By : Hiral Pandya Page : 16 of 32


 Label :
The Label widget implements a display box where you can place text or
images. The text displayed by this widget can be updated at any time. It is also
possible to underline part of the text (like to identify a keyboard shortcut) and
span the text across multiple lines.

Common Properties
Properties Description
This options controls where the text is positioned if the widget has more
anchor space than the text needs. The default is anchor=CENTER, which centers
the text in the available space.
bg The normal background color displayed behind the label and indicator.
Set this option equal to a bitmap or image object and the label will display
bitmap
that graphic.
bd The size of the border around the indicator. Default is 2 pixels.
If we set this option to a cursor name (arrow, dot etc.), the mouse cursor
cursor
will change to that pattern when it is over the checkbutton
If we are displaying text in this label (with the text or textvariable option,
font
the font option specifies in what font that text will be displayed.
If we are displaying text or a bitmap in this label, this option specifies the
fg color of the text. If you are displaying a bitmap, this is the color that will
appear at the position of the 1-bits in the bitmap.
height The vertical dimension of the new frame.
To display a static image in the label widget, set this option to an image
image
object.
Specifies how multiple lines of text will be aligned with respect to each
justify other: LEFT for flush left, CENTER for centered (the default), or RIGHT for
right-justified.
Extra space added to the left and right of the text within the widget.
padx
Default is 1.
Extra space added above and below the text within the widget.
pady
Default is 1.
Specifies the appearance of a decorative border around the label. The
relief
default is FLAT; for other values.
To display one or more lines of text in a label widget, set this option to a
text
string containing the text. Internal newlines ("\n") will force a line break.
To slave the text displayed in a label widget to a control variable of
textvariable class StringVar, set this option to that variable.
we can display an underline (_) below the nth letter of the text, counting
underline from 0, by setting this option to n. The default is underline=-1, which
means no underlining.
Width of the label in characters (not pixels!). If this option is not set, the
width label will be sized to fit its contents.
You can limit the number of characters in each line by setting this option
wraplength to the desired number. The default value, 0, means that lines will be
broken only at newlines.

Python Notes By : Hiral Pandya Page : 17 of 32


Example : Simple Label
from tkinter import *
frm = Tk()
[Link]("400x400")
[Link]("Python In HJD")

lbl = Label(frm, text="Hello, I'm Label Control")

[Link]()
[Link]()

Example : Formatted Label


from tkinter import *
import [Link] as font
top = Tk()
[Link]("400x400")
[Link]("Python In HJD")
myFont = [Link](family='Cambria',size=16,weight="bold")
var = StringVar()
lbl = Label(top, textvariable=var, relief=FLAT)
lbl['font'] = myFont
[Link](x = 70,y = 150)
[Link]("How are you doing?")
[Link]()

 Entry Fields (TextBox):


The Entry widget is used to provide the single line text-box to the user to
accept a value from the user. The Entry widget can be used to accept the text
strings from the user. It can only be used for one line of text from the user.

Python Notes By : Hiral Pandya Page : 18 of 32


Common Properties
Properties Description
bg The normal background color displayed behind the label and indicator.

bd The size of the border around the indicator. Default is 2 pixels.


A procedure to be called every time the user changes the state of this
command
checkbutton.
This option is to set a cursor name (arrow, dot etc.), the mouse cursor
cursor
will change to that pattern when it is over the checkbutton.
font The font used for the text.
By default, if text is selected within an Entry widget, it is automatically
exportselection exported to the clipboard. To avoid this exportation,
use exportselection=0.
fg The color used to render the text.

highlightcolor The color of the focus highlight when the checkbutton has the focus.
If the text contains multiple lines, this option controls how the text is
justify
justified: CENTER, LEFT, or RIGHT.
With the default value, relief=FLAT, the checkbutton does not stand
relief out from its background. You may set this option to any of the other
styles
selectbackground The background color to use displaying selected text.
The width of the border to use around selected text. The default is one
selectborderwidth
pixel
selectforeground The foreground (text) color of selected text.
Normally, the characters that the user types appear in the entry. To
show make a .password. entry that echoes each character as an asterisk,
set show="*".
The default is state=NORMAL, but you can use state=DISABLED to gray
state out the control and make it unresponsive. If the cursor is currently
over the checkbutton, the state is ACTIVE.
In order to be able to retrieve the current text from your entry widget,
textvariable you must set this option to an instance of the StringVar class.
The default width of a checkbutton is determined by the size of the
displayed image or text. This option can be set to a number of
width
characters and the checkbutton will always have room for that many
characters.
If users will often enter more text than the onscreen size of the widget,
xscrollcommand
Entry widget can be linked to a scrollbar.

Python Notes By : Hiral Pandya Page : 19 of 32


Common Methods :

Methods Description

Deletes characters from the widget, starting with the


one at index first, up to but not including the character
delete(first,last=None )
at position last. If the second argument is omitted,
only the single character at position first is deleted.

get() Returns the entry's current text as a string.

Set the insertion cursor just before the character at


icursor(index)
the given index.
Shift the contents of the entry so that the character at
index(index) the given index is the leftmost visible character.
Has no effect if the text fits entirely within the entry.

insert(index, s) Inserts string s before the character at the given index.

This method is used to make sure that the selection


select_adjust(index)
includes the character at the specified index.
Clears the selection. If there isn't currently a selection,
select_clear()
has no effect.
Sets the ANCHOR index position to the character
select_from(index)
selected by index, and selects that character.

select_present() If there is a selection, returns true, else returns false.

Sets the selection under program control. Selects the


text starting at the start index, up to but not including
select_range(start, end)
the character at the end index. The start position must
be before the end position.
Selects all the text from the ANCHOR position up to
select_to(index)
but not including the character at the given index.
This method is useful in linking the Entry widget to a
xview(index)
horizontal scrollbar.
Used to scroll the entry horizontally. The what
argument must be either UNITS, to scroll by character
xview_scroll(number, what) widths, or PAGES, to scroll by chunks the size of the
entry widget. The number is positive to scroll left to
right, negative to scroll right to left.

Python Notes By : Hiral Pandya Page : 20 of 32


Example : Simple TextBox (Entry Field)
from tkinter import *
import [Link] as font
frm = Tk()
[Link]("400x150")
[Link]("Python In HJD")
#Creating Lable
lblFont = [Link](family='Verdana',size=12,weight="normal")
lblName = Label(frm, text="User Name :
",anchor="w",justify="left",width=150)
lblName['font'] = lblFont
[Link](x = 53,y = 5)
#Creating TextBox (Entry Field)
txtName = Entry(frm,width=20,bd=1,relief="solid")
txtName['font']=lblFont
[Link](x = 168, y = 5)
#Creating Lable
lblPass = Label(frm, text="Password :
",anchor="w",justify="right",width=150)
lblPass['font'] = lblFont
[Link](x = 66,y = 35)
#Creating TextBox (Entry Field)
txtPass = Entry(frm,width=20,bd=1,relief="solid")
txtPass ['font']=lblFont
[Link](x = 168, y = 35)
#Creating Button
btnSubmit = Button(frm, text = "Submit",activebackground =
"yellow",activeforeground = "blue",relief="solid")
btnSubmit['font'] = lblFont
[Link](x = 168, y = 70)
#Creating Lable
lblMsg = Label(frm, text="LogIn Status",anchor="w",fg="Red")
lblMsg['font'] = [Link](family='calibri',size=14)
[Link](x = 168,y = 105)
[Link]()

Python Notes By : Hiral Pandya Page : 21 of 32


Example : TextBox (Entry Field) With Function
from tkinter import *
import [Link] as font
frm = Tk()
[Link]("400x150")
[Link]("Python In HJD")
lblFont = [Link](family='Verdana',size=12,weight="normal")
lblName = Label(frm, text="User Name :
",anchor="w",justify="left",width=150)
lblName['font'] = lblFont
[Link](x = 53,y = 5)
txtName = Entry(frm,width=20,bd=1,relief="solid")
txtName['font']=lblFont
[Link](x = 168, y = 5)
lblPass = Label(frm, text="Password :
",anchor="w",justify="right",width=150)
lblPass['font'] = lblFont
[Link](x = 66,y = 35)
txtPass = Entry(frm,width=20,bd=1,relief="solid")
txtPass ['font']=lblFont
[Link](x = 168, y = 35)
lblMsg = Label(frm,anchor="w")
lblMsg['font'] = [Link](family='calibri',size=14,weight="bold")
[Link](x = 168,y = 105)
#Creating Function to Get Values from TextBox
def GetDataFromTextBox():
if([Link]() == "admin" and [Link]() == "admin"):
[Link](fg="Navy")
[Link](text = "WelCome, "+[Link]())
else:
[Link](fg="Red")
[Link](text = "Invalid Credentials")
btnSubmit = Button(frm,text = "Log In",command = GetDataFromTextBox,
relief="solid")
btnSubmit['font'] = lblFont
[Link](x = 168, y = 70)
[Link]()

Python Notes By : Hiral Pandya Page : 22 of 32


 ListBox:
Common Properties
Properties Description
The normal background color displayed behind the label and
bg
indicator.
bd The size of the border around the indicator. Default is 2 pixels.

cursor The cursor that appears when the mouse is over the listbox.

font The font used for the text in the listbox

fg The color used for the text in the listbox.

height Number of lines (not pixels!) shown in the listbox. Default is 10.

highlightcolor Color shown in the focus highlight when the widget has the focus.

highlightthickness Thickness of the focus highlight.


Selects three-dimensional border shading effects.
relief
The default is SUNKEN.
selectbackground The background color to use displaying selected text.
Determines how many items can be selected, and how mouse drags
affect the selection :
• BROWSE : Normally, you can only select one line out of a listbox.
If you click on an item and then drag to a different line, the
selection will follow the mouse. This is the default.
selectmode • SINGLE : You can only select one line, and you can't drag the
mouse. wherever you click button 1, that line is selected.
• MULTIPLE : You can select any number of lines at once. Clicking on
any line toggles whether or not it is selected.
• EXTENDED : You can select any adjacent group of lines at once by
clicking on the first line and dragging to the last line.
width The width of the widget in characters. The default is 20.
If we want to allow the user to scroll the listbox horizontally,
xscrollcommand
We can link our listbox widget to a horizontal scrollbar.
If we want to allow the user to scroll the listbox vertically,
yscrollcommand
We can link our listbox widget to a vertical scrollbar.

Python Notes By : Hiral Pandya Page : 23 of 32


Common Methods
Methods Description
activate(index) Selects the line specifies by the given index.
Returns a tuple containing the line numbers of the
curselection() selected element or elements, counting from 0. If
nothing is selected, returns an empty tuple.
Deletes the lines whose indices are in the range [first,
delete(first, last=None) last]. If the second argument is omitted, the single line
with index first is deleted.
Returns a tuple containing the text of the lines with
indices from first to last, inclusive. If the second
get(first, last=None)
argument is omitted, returns the text of the line closest
to first.
If possible, positions the visible part of the listbox so that
index(i)
the line containing index i is at the top of the widget.
Insert one or more new lines into the listbox before the
insert(index, *elements) line specified by index. Use END as the first argument if
you want to add new lines to the end of the listbox.
Return the index of the visible line closest to the y-
nearest(y)
coordinate y relative to the listbox widget.
Adjust the position of the listbox so that the line referred
see(index)
to by index is visible.

size() Returns the number of lines in the listbox.


To make the listbox horizontally scrollable, set the
xview() command option of the associated horizontal scrollbar to
this method
Scroll the listbox so that the leftmost fraction of the
xview_moveto(fraction) width of its longest line is outside the left side of the
listbox. Fraction is in the range [0,1].
Scrolls the listbox horizontally. For the what argument,
use either UNITS to scroll by characters, or PAGES to
xview_scroll(number, what)
scroll by pages, that is, by the width of the listbox. The
number argument tells how many to scroll.
To make the listbox vertically scrollable, set the
yview() command option of the associated vertical scrollbar to
this method
Scroll the listbox so that the top fraction of the width of
yview_moveto(fraction) its longest line is outside the left side of the listbox.
Fraction is in the range [0,1].
Scrolls the listbox vertically. For the what argument, use
either UNITS to scroll by lines, or PAGES to scroll by
yview_scroll(number, what) pages, that is, by the height of the listbox. The number
argument tells how many to scroll.

Python Notes By : Hiral Pandya Page : 24 of 32


Example : ListBox With Event
import tkinter as tk
from tkinter import ttk
from [Link] import showinfo
import [Link] as font
# create the root window
root = [Link]()
[Link](400x400)
[Link](False, False)
[Link]('Listbox Demo')
[Link](0, weight=1)
[Link](0, weight=1)
# create a list box
langs = ('Java', 'C#.NET', 'C', 'C++', 'Python',
'[Link]', 'JavaScript', 'PHP', 'Android')
langs_var = [Link](value=langs)
listbox = [Link](root,listvariable=langs_var, height=6,
selectmode='single')
listbox['font']=[Link](family='Verdana',size=14)
[Link]( column=0,row=0,sticky='nwes')
# handle event
def items_selected(event):
""" handle item selected event """
# get selected indices
selected_indices = [Link]()
# get selected items
selected_langs = ",".join([[Link](i) for i in
selected_indices])
msg = f'You selected: {selected_langs}'
showinfo(title='Information', message=msg)
[Link]('<<ListboxSelect>>', items_selected)
[Link]()

Python Notes By : Hiral Pandya Page : 25 of 32


 ComboBox: ComboBox support major properties and methods of
Listbox.
Example : ComboBox With Event
import tkinter as tk
from tkinter import ttk
from [Link] import showinfo
import [Link] as font

# create the root window


frm = [Link]()
[Link]('400x400')
[Link]('ComboBox Demo')

# create a Combobox
cmb = [Link](frm,width=20)
cmb['font']=[Link](family='Arial',size=10)
cmb['values'] = ('Java', 'C#.NET', 'C', 'C++', 'Python',
'[Link]', 'JavaScript', 'PHP', 'Android')
cmb['state'] = 'readonly'
[Link](column = 0, row = 0)
[Link](fill=tk.X, padx=5, pady=5)

# handle SelectedIndexChanged event of ComboBox


def items_selected(event):
msg = f'You Have Selected : {[Link]()}'
showinfo(title='Selected Item', message=msg)

# Bind event of ComboBox


[Link]('<<ComboboxSelected>>', items_selected)
[Link]()

Python Notes By : Hiral Pandya Page : 26 of 32


 CheckBox (Checkbutton):
The Checkbutton widget is a standard Tkinter widget that is used to implement
on/off selections. Checkbuttons can contain text or images. When the button
is pressed, Tkinter calls that function or method.

Properties of CheckBox (checkbutton)


Properties Description
bitmap This option used to display a monochrome image on a button.
This option is associated with a function to be called when the
command
state of the checkbutton is changed.
By using this option, the mouse cursor will change to that
cursor
pattern when it is over the checkbutton.
The foreground color used to render the text of a disabled
disabledforeground checkbutton. The default is a stippled version of the default
foreground color.
image This option used to display a graphic image on the button.
The associated control variable is set to 0 by default if the
offvalue button is unchecked. We can change the state of an unchecked
variable to some other one.
The associated control variable is set to 1 by default if the
onvalue button is checked. We can change the state of the checked
variable to some other one.
It represents the state of the checkbutton. By default, it is set
to normal. We can change it to DISABLED to make the
state
checkbutton unresponsive. The state of the checkbutton is
ACTIVE when it is under focus.
This option used to represents the associated variable that
variable
tracks the state of the checkbutton.
This option used to represents the width of the checkbutton.
width and also represented in the number of characters that are
represented in the form of texts.
wraplength This option will be broken text into the number of pieces.

Methods of CheckBox (checkbutton)


Methods Description
deselect() This method is called to turn off the checkbutton.
The checkbutton is flashed between the active and
flash()
normal colors.
This method will invoke the method associated with the
invoke()
checkbutton.
select() This method is called to turn on the checkbutton.
This method is used to toggle between the different
toggle()
Checkbuttons.

Python Notes By : Hiral Pandya Page : 27 of 32


Example : Simple Checkbutton
from tkinter import *
import [Link] as font
frm = Tk()
[Link]("300x200")
[Link]("Python In HJD")
lblName = Label(frm, text="Select Gender :
",anchor="w",justify="left",width=150)
lblName['font'] =
[Link](family='Verdana',size=12,weight="normal")
[Link](x = 5,y = 5)
lbl = Label(frm,anchor="w",justify="left",width=150)
lbl['font'] = [Link](family='Verdana',size=12,weight="normal")
[Link](x = 5,y = 125)
m=IntVar()
f=IntVar()
chkMale = Checkbutton(frm, text = "Male", variable=m)
chkMale['font'] =
[Link](family='Cambria',size=14,weight="normal")
[Link](x = 5,y = 30)
chkFemale = Checkbutton(frm, text = "Female", variable=f)
chkFemale['font'] =
[Link](family='Cambria',size=14,weight="normal")
[Link](x = 5,y = 55)
def RetuChkValue():
if([Link]()== 1 and [Link]()==1):
[Link](text="Gender = Male & Female")
elif([Link]()== 1):
[Link](text="Gender = Male")
elif([Link]()== 1):
[Link](text="Gender = Female")
else:
[Link](text="Gender Is Not Selected")
btnSubmit = Button(frm,text = "Submit", command=RetuChkValue,
relief="solid")
btnSubmit['font'] =
[Link](family='Verdana',size=12,weight="normal")
[Link](x = 10, y = 90)
[Link]()

Python Notes By : Hiral Pandya Page : 28 of 32


 Radiobutton:
This widget implements a multiple-choice button, which is a way to offer many
possible selections to the user and lets user choose only one of them. In order
to implement this functionality, each group of radiobuttons must be
associated to the same variable and each one of the buttons must symbolize
a single value. We can use the Tab key to switch from one radionbutton to
another.
Example : Simple Radiobutton
from tkinter import *
import [Link] as font
frm = Tk()
[Link]("300x200")
[Link]("Python In HJD")
lblName = Label(frm, text="Select Gender :
",anchor="w",justify="left",width=150)
lblName['font'] =
[Link](family='Verdana',size=12,weight="normal")
[Link](x = 5,y = 5)
lblRes = Label(frm,anchor="w",justify="left",width=150)
lblRes['font'] =
[Link](family='Verdana',size=12,weight="normal")
[Link](x = 5,y = 125)
g=IntVar()
def RetuChkValue():
if([Link]() == 1):
[Link](text = "You Have Selected : Male")
elif([Link]() == 2):
[Link](text = "You Have Selected : Female")
else : [Link](text = "You Have Not Selected Any
Option")
rdbMale = Radiobutton(frm, text = "Male", variable=g,value=1)
rdbMale['font'] =
[Link](family='Cambria',size=14,weight="normal")
[Link](x = 5,y = 30)
rdbFemale = Radiobutton(frm, text = "Female",
variable=g,value=2)
rdbFemale['font'] =
[Link](family='Cambria',size=14,weight="normal")
[Link](x = 5,y = 55)
btnSubmit = Button(frm,text = "Submit", command=RetuChkValue,
relief="solid")
btnSubmit['font'] =
[Link](family='Verdana',size=12,weight="normal")
[Link](x = 10, y = 90)
[Link]()

Python Notes By : Hiral Pandya Page : 29 of 32


 Frame:
The Frame widget is very important for the process of grouping and organizing
other widgets in a somehow friendly way. It works like a container, which is
responsible for arranging the position of other widgets. It uses rectangular
areas in the screen to organize the layout and to provide padding of these
widgets. A frame can also be used as a foundation class to implement complex
widgets.

Properties of Frame

Properties Description
The normal background color displayed behind the label and
bg
indicator.

The size of the border around the indicator.


bd
Default is 2 pixels.

If this option is set to a cursor name (arrow, dot etc.), the

cursor mouse cursor will change to that pattern when it is over the
checkbutton.

height The vertical dimension of the new frame.

Color of the focus highlight when the frame does not have
highlightbackground
focus.

Color shown in the focus highlight when the frame has the
highlightcolor
focus.

highlightthickness Thickness of the focus highlight.

With the default value, relief=FLAT, the frame does not stand

relief out from its background.

We may set this option to any of the other styles

width This option will set width of frame

Python Notes By : Hiral Pandya Page : 30 of 32


Example : Simple Frame
from tkinter import *
import [Link] as font
from [Link] import showinfo

frm = Tk()
[Link]("300x200")
[Link]("Python In HJD")

lblName = Label(frm, text="Select Gender :


",anchor="w",justify="left",width=150)
lblName['font'] =
[Link](family='Verdana',size=12,weight="normal")
[Link](x = 5,y = 20)

g=IntVar()

def RetuChkValue():
if([Link]() == 1):
showinfo("Selected Gender", "You Have Selected : Male")
elif([Link]() == 2):
showinfo('Selected Gender', "You Have Selected : Female")
else : showinfo("Selected Gender", "You Have Not Selected Any
Option")

# Creating Frame
fmGen =
Frame(frm,width=120,height=80,padx=5,pady=0,bd=0,highlightbackground
="Navy", highlightthickness=2)
[Link](side=LEFT)

# Creating Radiobutton and add it to Frame


rdbMale = Radiobutton(fmGen, text = "Male", variable=g,value=1)
rdbMale['font'] =
[Link](family='Cambria',size=14,weight="normal")
[Link](x = 0,y = 5)

# Creating Radiobutton and add it to Frame


rdbFemale = Radiobutton(fmGen, text = "Female", variable=g,value=2)
rdbFemale['font'] =
[Link](family='Cambria',size=14,weight="normal")
[Link](x = 0,y = 40)

btnSubmit = Button(frm,text = "Submit", command=RetuChkValue,


relief="solid")
btnSubmit['font'] =
[Link](family='Verdana',size=12,weight="normal")
[Link](x = 10, y = 150)
[Link]()

Python Notes By : Hiral Pandya Page : 31 of 32


Example : Multiple Frames(Nested Frames)
from tkinter import *

class MyApp:
def __init__(self, parent):

[Link] = parent

self.myContainer1 = Frame(parent)
[Link]()

self.top_frame = Frame(self.myContainer1)
self.top_frame.pack(side=TOP,
fill=BOTH,
expand=YES,
)

self.left_frame = Frame(self.top_frame, background="red",


borderwidth=5, relief=RIDGE,
height=250,
width=50,
)
self.left_frame.pack(side=LEFT,
fill=BOTH,
expand=YES,
)

self.right_frame = Frame(self.top_frame, background="tan",


borderwidth=5, relief=RIDGE,
width=250,
)
self.right_frame.pack(side=RIGHT,
fill=BOTH,
expand=YES,
)

root = Tk()
[Link]("Python In HJD")
myapp = MyApp(root)
[Link]()

Python Notes By : Hiral Pandya Page : 32 of 32

You might also like