Unit 4 Python
Unit 4 Python
Introduction
Python allows user to connect to various databases through database interfaces. Python’s
database interface is DB-API(DataBase-Application Programming Interface). User can choose
the database which has to be connected to python. Python DB-API supports a large number of
databases like Oracle,MS-SQL server 2000,MYSQL,mSQL,Sysbase etc. For using each database
user need to download separate DB-API modules.
CONNECTING TO A DATABASE
Import pymysql module. This module’s method is used to communicate with the MySQL
database.
To create a connection between the MySQL database and the python application, the connect()
method of pymysql module is used. Pass the database details like HostName, username,
database password,database name in the method call. This method returns the connection
object.
3. Create the cursor object
Cursor object can be created by calling cursor() method. Cursor object is used to perform
various SQL operations.
The execute() method run the SQL query and return the result.
The close() method is used to close the database connection and release the resources. The
syntax for closing connection is db.close() where db is connection object.
import pymysql
db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)
cursor=db.cursor()
cursor.execute(“SELECT VERSION()”)
data=cursor.fetchone()
print(“Database version:”,data)
db.close()
Output
Database version:5.6.36-log
In above example, a connection is established with the data source and a connection object is
returned. The connection object is saved to db. If connection is not properly established, db will
store the value None. The database object db is used to create a cursor object cursor and this
cursor is used for executing SQL queries. At the end, database connection is closed and
resources are released.
Note:
In above example, database called SAMPLE is initially created. The user id and password used to
access SAMPLE database is “user” and “pass” respectively. A table called STUDENT in SAMPLE
database is created. The table STUDENT has fields ROLLNO,NAME,AGE,COURSE,GRADE
CREATING TABLES
After establishing connection with database, tables can be created. Creation of tables are
performed in Python with the help of execute() statement.
Example Program:
import pymysql
db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)
cursor=db.cursor()
cursor.execute(sql)
db.commit()
db.close()
……………………………………………………………………………………………………………………………………………
The above program creates a table called DEPT with fields DEPTNO,DEPT_NAME and
LOCATION. The SQL statement for creating the table is stored in sql and the sql is passed to
execute() method for creating the table.
INSERT OPERATION
After creating table, values are inserted to the table. The values can be inserted using the
INSERT statement of SQL.
Example program:
import pymysql
db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)
cursor=db.cursor()
cursor.execute(sql)
db.commit()
db.close()
……………………………………………………………………………………………………………………………………………
After execution of this program, a record with specified values will be inserted into the DEPT
table.
UPDATE OPERATION
UPDATE operation is done to modify existing values available in the table. One or more records
can be updated at same time.
import pymysql
db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)
cursor=db.cursor()
cursor.execute(sql)
db.commit()
db.close()
…………………………………………………………………………………………………………………………………………………..
The above example updates the location of sales department from Chennai to Delhi. If there is
more than one record with the satisfied condition, then all those records will be updated.
DELETE OPERATION
DELETE operation is performed to delete some undesired or unwanted records from a table.
DELETE operation can be specified with or without conditions.
Example program:
import pymysql
db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)
cursor=db.cursor()
cursor.execute(sql)
db.commit()
db.close()
……………………………………………………………………………………………………………………
The above example will delete all the records with location Delhi.
READ operation is used to fetch desired records from a database. There are several methods for
fetching records from a database. After establishing connection, queries can be made to
database.
1. fetchone()
2. fetchall()
3. rowcount
Note: rowcount is an attribute
1. fetchone()
It fetches the next row of a query result. A result set is an object that is returned when a cursor
object is used to query a table.
Example program:
import pymysql
db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)
cursor=db.cursor()
cursor.execute(sql)
row=cursor.fetchone()
if row:
print(“Location:”,row[0])
db.close()
Output
Location:Delhi
2. fetchall()
It fetches all the rows in a result set. If some rows have already been extracted from the result
set, then it retrieves the remaining rows from the result set.
Example program:
import pymysql
db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)
cursor=db.cursor()
cursor.execute(sql)
rows=cursor.fetchall()
print(“Location:”,row[0])
db.close()
Output
Location:Delhi
Location:Chennai
Location:Mumbai
3. rowcount : This is a read-only attribute and returns the number of rows that were
affected by an execute() method.
Example Program
import pymysql
db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)
cursor=db.cursor()
cursor.execute(sql)
numrows=cursor.rowcount
print(“Number of Records:”,numrows.rowcount)
db.close()
Output
Number of Records: 3
TRANSACTION CONTROL
A transaction is a logical unit of work that contains one or more SQL statements. A transaction
is an atomic unit. The effects of all the SQL statements in a transaction can be either all
committed(applied to the database) or all rolled back(undone from a database)
1. Atomicity
2. Consistency
3. Isolation
4. Durability
Atomicity: Atomicity ensures that all operations within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure, and previous
operations are rolled back to their former state.
Consistency: Consistency ensures that the database properly changes states upon a successfully
committed transaction.
Durability : Durability ensures that the result or effect of a committed transaction persists in
case of a system failure.
COMMIT Operation
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database. The COMMIT command saves all transactions to the database
since the last COMMIT or ROLLBACK command. The syntax for a commit statement is
db.commit().
ROLLBACK Operation
The ROLLBACK is the transactional command used to undo transactions that have not already
been saved to the database. The ROLLBACK command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued. The syntax for rollback is
db.rollback().
import pymysql
db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)
cursor=db.cursor()
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
In the above example, commit() statement makes changes to the database permanently. If
there is any error, rollback() is called to undo the changes.
Python provides various options for developing Graphical User Interfaces(GUIs).Tkinter is the
Python interface for Tk. There are other Python interfaces like wxPython and JPython. But the
most popular interface is Tkinter.
Tkinter,wxPython and JPython are the interfaces for developing Graphical User
Interfaces(GUIs).
……………………………………………………………………………………………………………………………………………………
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a
fast and easy way to create GUI applications.
Tkinter provides various controls such as buttons,labels and text boxes used in a GUI
application. These controls are called widgets. There are several types of widgets in Tkinter.
1. Label widget
2. Message widget
3. Entry widget
4. Text widget
5. Button widget
6. Radio Button
7. Checkbutton
Label Widget
A label is a Tkinter widget class which is used to display text or an image. The label is a widget
that the user just views but not interacts with. The text displayed by this widget can be updated
at any time.
label=Label(master,option, …….)
The parameter master represents the parent window and option is the list of commonly used
options for Label widget. Options can be used as key-value pairs separated by commas.
Option Description
bg The normal background color displayed behind the label.
fg Specifies the color of text
anchor This options controls where the text is positioned if the widget has more space
than the text needs. The values for this attribute are N,NE,E,SE,S,SW,W,NW
image To display a static image in the label widget, set this option to an image object.
padx Extra space added to the left and right of the text within the widget.
pady Extra space added above and below the text within the widget
width Width of label in characters.
justify Specify how multiple lines of text will be aligned with respect to each other.(i.e
LEFT,CENTER,RIGHT)
text To display one or more lines of text in a label widget, set this option to a string
containing text.
Example program: (Label widget)
root=Tk()
label.pack()
root.mainloop()
Output
When the above code is executed, a label with Welcome to Python Programming is displayed in
Garamond font. The pack() method tells Tk to fit the size of the window to the given text. The
window won’t appear until, we enter the Tkinter event loop. The script will remain in the event
loop until we close the window.
Message Widget
The message widget is used to display short text messages. The message widget is similar in its
functionality to the label widget, but it is more flexible in displaying text.
For example, the font can be changed while the label widget can only display text in a single
font.
Message widget provides a multiline object which allows text to span more than one line. The
text is automatically broken into lines and justified.
Syntax:
msg=Message(master,option, …..)
The parameter master represents the parent window and option is the list of commonly used
options for this widget. Options can be used as key-value pairs separated by commas.
Example program:
root=Tk()
msg.pack()
root.mainloop()
Output
Entry Widget
Entry widgets are the basic widgets of Tkinter used to get input. (i.e text strings from the user of
an application) .Entry widget allows the user to enter a single line of text. If the user enters a
string, which is longer than the available display space of the widget, the content will be
scrolled. The string cannot be seen in full. An entry widget can use only single font.
msg=Entry(master,option, …..)
The parameter master represents the parent window and option is the list of commonly used
options for this widget. Options can be used as key-value pairs separated by commas.
Option Description
bg The normal background color displayed behind the label.
fg Specifies the color of text
justify Specify how multiple lines of text will be aligned with respect to each
other.(i.e LEFT,CENTER,RIGHT)
font The font used for the text
bd The size of border around the indicator. Default is 2 pixels.
show Normally the characters that the user types appears in the entry. To display
entered character as asterisk, set show=”*”
state Default state is NORMAL. If state=DISABLED, Entry widget becomes
unresponsive.(i.e User cannot enter text)
selectbackground The background color to use for displaying selected text
selectforeground The text (foreground) color of selected text.
Example program:
top=Tk()
L1=Label(top,text="User Name").grid(row=0)
L2=Label(top,text="Password").grid(row=1)
E1=Entry(top,bg="red",fg="white").grid(row=0,column=1)
E2=Entry(top,bg="red",fg="white").grid(row=1,column=1)
top.mainloop()
Output
Method Description
get() Return’s the entry’s current text as a string
icursor(index) Set the insertion cursor just before the character at the given index.
insert(index,s) Insert string s before the character at the given index.
select_clear() Clears the selection.
select_present() If there is a selection, returns true, else returns false.
Text Widget
A text widget is used for multi-line text area. The Tkinter text widget is very powerful, flexible
and can be used for a wide range of tasks. Text widget can be used in simple text editors or web
browsers. The text widget can be used to display links ,images and HTML. User can embed
windows and images in the text.
t=Text(master,option,…)
The parameter master represents the parent window and option is the list of commonly used
options for this widget. Options can be used as key-value pairs separated by commas.
Option Description
bg The default background color of the text widget
bd The width of the border around the text widget
cursor The cursor that will appear when the mouse is over the text widget
font The default font for text inserted into the widget
fg The color used for texts within the widget
padx The size of internal padding added to the left and right of the text area.
pady The size of internal padding added above and below the text area.
width The width of widget in characters
state Default state is NORMAL. If state=DISABLED, text widget becomes
unresponsive.
Example program:
root=Tk()
t=Text(root,height=2,width=30)
t.pack()
root.mainloop()
Output
tkMessageBox
The tkMessageBox module is used to display message boxes in applications. This module
provides a number of functions that can be used to display an appropriate message.
1. showinfo()
2. showwarning()
3. showerror()
4. askquestion()
5. askokcancel
6. askyesno()
7. askretryignore()
tkMessageBox.FunctionName(title,message[,options])
where FunctionName is the name of the appropriate message box function, title is the text to
be displayed in the title bar of a message box, message is the text to be displayed as a message
and options are alternative choices that are used to tailor a standard message box.
Example program:
root=Tk()
def hello():
hello()
root.mainloop()
Output
Button Widget
The button is a widget which is designed for the user to interact with. i.e If the button is
pressed by mouse, some action might be started. Button can contain text and images. Button
can display text in a single font. The text of button can span more than one line. A Python
function or method can be associated with a button. This function or method will be executed,
if the button is pressed.
b=Button(master,option, ……)
where the parameter master represents the parent window and option is the list of most
commonly used options for this widget. These options can be used as key-value pairs separated
by commas.
Option Description
bg Background color
fg Foreground(text) color
font Text font to be used for the button’s label
image Image to be displayed on the button
command Function or method to be called when the button is clicked.
state Set this option to DISABLED to make button unresponsive. Default value is
NORMAL
a) flash()
b) invoke()
a) flash() - Causes the button to flash several times between active and normal colors.
b) invoke() - Calls the button’s callback and returns what the function returns.
root=Tk()
def helloCallBack():
messagebox.showinfo("Python","Python Programming")
B=Button(root,text="Python",command=helloCallBack)
B.pack()
root.mainloop()
Output
Radio Button
A radio button allows the user to choose exactly one of a predefined set of options. Radio
buttons can contain text or images. The button can only display text in a single font. A python
function or method can be associated with a radio button. This function or method will be
called, if radio button is pressed. Each group of radio button widgets is associated with the
same variable. Pushing a button changes the value of this variable to a predefined certain value.
r=Radiobutton(master,option,….)
where the parameter master represents the parent window and option is the list of most
commonly used options for this widget. These options can be used as key-value pairs separated
by commas.
Option Description
font The font used for the text
command A procedure to be called every time the user changes the state of radio
button
activebackground The background color when the mouse is over the radio button
activeforeground The foreground color when the mouse is over the radio button
padx Space to leave to the left and right of the radio button and text
pady Space to leave above and below the radio button and text.
state The default state is NORMAL. The state is DISABLED, then radio button
becomes unresponsive.
text The label displayed next to the radio button.
Example program:
root=Tk()
label=Label(root)
def sel():
label.config(text=selection)
var=StringVar()
var.set("Windows")
r1=Radiobutton(root,text="Windows",variable=var,value="Windows",command=sel)
r1.pack()
r2=Radiobutton(root,text="Solaris",variable=var,value="Solaris",command=sel)
r2.pack()
r3=Radiobutton(root,text="Linux",variable=var,value="Linux",command=sel)
r3.pack()
label.pack()
root.mainloop()
Output
Checkbutton (Checkbox)
Checkboxes are widgets that permit the user to make multiple selections from a number of
different options. Checkboxes are shown on the screen as square boxes that can contain white
spaces(for false, i.e not checked) or a tick mark or X (for true, i.e checked)
A caption describing the meaning of the checkbox is usually shown adjacent to the checkbox.
The state of a checkbox is changed by clicking the mouse on the box.
c=Checkbutton(master,option,……)
where parameter master represents the parent window and option is the list of most
commonly used options for this widget. These options can be used as key-value pairs separated
by commas.
Example program:
root=Tk()
var1=IntVar()
var2=IntVar()
var3=IntVar()
var1.set(0)
var2.set(0)
var3.set(0)
def sel():
if var1.get()==1:
if var2.get()==1:
if var3.get()==1:
c1=Checkbutton(root,text="Windows",variable=var1,onvalue=1,offvalue=0,command=sel)
c1.pack()
c2=Checkbutton(root,text="Solaris",variable=var2,onvalue=1,offvalue=0,command=sel)
c2.pack()
c3=Checkbutton(root,text="Linux",variable=var3,onvalue=1,offvalue=0,command=sel)
c3.pack()
root.mainloop()
Output
Listbox
The Listbox widget is used to display a list of alternatives. The listbox can only contain text
items, and all items must have the same font and color. Listboxes are used to select from a
group of textual items. Depending on how the listbox is configured, the user can select one or
many items from that list.
c=Listbox(master,option, ….)
where the parameter master represents the parent window and option is the list of most
commonly used options for this widget. These options can be used as key-value pairs separated
by commas.
Option Description
bg Background color
fg The color used for the text in the listbox
font The font used for the text in the listbox
cursor The cursor that appears when the mouse is over the listbox. (i.e arrow,dot)
height Number of lines shown in the listbox.
width The width of the widget in characters.
selectbackground The background color to use for displaying selected text.
selectmode Determines how many items can be selected. i.e SINGLE, MULTIPLE
Option Description
activate(index) Selects the line specified by the given index.
size() Returns the number of lines in the listbox
insert(index,*elements) Insert one or more lines into the listbox before the line specified by
the index.To add new lines to the end of the listbox, END is used as
first argument.
delete(first,last=None) Deletes the line whose indices are in the range[first,last]. If the
second argument is omitted, the single line with index first is deleted.
curselection() Returns a tuple containing the line number of the selected elements.
Example program:
master=Tk()
listbox=Listbox(master)
listbox.pack()
listbox.insert(END,item)
master.mainloop()
Output
Menu Widget
a) Pop-up
b) Top level
c) Pull down
Menus are commonly used to provide convenient access to options like opening any
file, quitting any task, and manipulating data in an application.
m=Menu(master,option,….)
where the parameter master represents the parent window and option is the list of most
commonly used options for this widget. These options can be used as key-values pairs
separated by commas.
Option Description
image To display an image on menubutton
font The font type of the text of the widget.
fg The foreground color of the widget
cursor The cursor that appears when the mouse is over the choices. (i.e arrow,dot)
bd The width of border around all the choices
postcommand This option is set to a procedure and that procedure is called when mouse is
over the menu
Option Description
add_command(options) Adds a menu item to the menu
add_cascade(options) Creates a new hierarchical menu by
associating a given menu to a parent menu
add_radiobutton(options) Creates a radio button menu item
add_checkbutton(options) Creates a check button menu item
add(type,options) Adds a specific type of menu item to the menu
delete(startindex[,endindex]) Deletes the menu items ranging from
startindex to endindex.
index(item) Returns the index number of the given menu
item label
Example program:
root=Tk()
def hello():
print("hello!")
menubar.add_command(label="Hello!", command=hello)
menubar.add_command(label="Quit!", command=root.quit)
root.config(menu=menubar)
root.mainloop()
Output
Menubutton Widget
A menubutton is the part of a drop-down menu that stays on the screen all the time. Every
menubutton is associated with a Menu widget that can display the choices for that menubutton
when the user clicks on it.
m=Menubutton(master,option,…..)
where the parameter master represents the parent window and option is the list of most
commonly used options for this widget. These options can be used as key-value pairs separated
by commas.
Option Description
activebackground The background color when the mouse is over the menubutton
activeforeground The foreground color when the mouse is over the menubutton
cursor The cursor that appears when the mouse is over menubutton
padx The space to leave to the left and right of the text of the menubutton
pady The space to leave above and below the text of the menubutton
state Normally, menubuttons respond to the mouse. Set state=DISABLED to
make menubutton unresponsive.
width The width of the widget in characters.
Example program:
top=Tk()
mb=Menubutton(top,text="Flowers")
mb.grid()
mb.menu=Menu(mb,tearoff=0)
mb["menu"]=mb.menu
rose=IntVar()
lotus=IntVar()
mb.menu.add_checkbutton(label="Rose",variable=rose)
mb.menu.add_checkbutton(label="Lotus",variable=lotus)
mb.pack()
top.mainloop()
Output
Scrollbar
Scrollbar widget is used to implement scrolled listboxes, canvases and text fields. Horizontal
scrollbars can be used with the entry widget.
s=Scrollbar(master,option,……..)
where the parameter master represents the parent window and option is the list of most
commonly used options for this widget. These options are used as key-value pairs separated by
commas.
Option Description
activebackground The color of the slider and arrowheads when the mouse is over them
command A procedure to be called whenever the scrollbar is moved
cursor The cursor that appears when the mouse is over the scrollbar (i.e
arrow,dot)
width Width of the scrollbar
orient Set orient=HORIZONTAL for a horizontal scrollbar and orient=VERTICAL for
a vertical scrollbar
scrollbar has two commands get() and set()
1) get() – Returns two numbers(a,b) describing the current position of the slider. The a
value gives the position of the left or top edge of the slider for horizontal and vertical
scrollbar respectively. The b value gives the position of the right or bottom edge.
2) set(first,last) – To connect a scrollbar to another widget w, set w’s xscrollcommand or
yscrollcommand to the scrollbar’s set() method.
Example program:
root=Tk()
scrollbar=Scrollbar(root)
scrollbar.pack(side=RIGHT,fill=Y)
mylist=Listbox(root,yscrollcommand=scrollbar.set)
mylist.pack(side=LEFT,fill=BOTH)
scrollbar.config(command=mylist.yview)
root.mainloop()
Output
Scale Widget(Slider Widget)
A slider is a tkinter object with which a user can set a value by moving an indicator. Sliders can
be vertically or horizontally arranged. A slider is created with the scale() method. Using the
scale widget creates a graphical object, which allows the user to select a numerical value by
moving a knob along a scale of a range of values. The minimum and maximum values can be set
as parameters. Slider can be horizontally and vertically positioned.
s=Scale(master, option,…..)
where the parameter master represents the parent window and option is the list of most
commonly used options for this widget. These options can be used as key-value pairs separated
by commas.
Option Description
length The length of the scale widget.
orient Set orient=HORIZONTAL if scale has to run along the x-dimension. Set
orient=VERTICAL if scale has to run along the y-dimension.
font The font used for the label
fg The color of the text used for label
state Scale widgets respond to mouse events. Set state=DISABLED to make the
widget unresponsive.
showvalue Normally, the current value of the scale is displayed in text form by the
slider.(Above slider for horizontal scales and left of the slider for vertical
scales)
sliderlength Normally slider is 30 pixels along the length of the scale. The sliderlength
can be changed to any desired length.
from_ A float or integer value that defines one end of the scale’s range.
to A float or integer value that defines one end of the scale’s range. The other
end is defined by the from_ option.
tickinterval To display periodic scale values, set this option to a number and ticks will
be displayed on multiples of that value.
Example program:
def show_values():
print(w1.get(),w2.get())
master=Tk()
w1=Scale(master,from_=0,to=42,tickinterval=8)
w1.set(19)
w1.pack()
w2=Scale(master,from_=0, to=20,tickinterval=10,orient=HORIZONTAL)
w2.set(23)
w2.pack()
b1=Button(master,text="Show",command=show_values)
b1.pack()
master.mainloop()
Output
Canvas
Canvas widget supplies graphics facilities for tkinter. Graphical objects are lines,circles and
images. Using this widget it is possible to draw graphs,plots and implement various kind of
custom widgets.
c=Canvas(master,option=value,….)
The parameter master represents the parent window and option is the list of most commonly
used options for this widget. These options can be used as key-value pairs separated by
commas.
Option Description
bd Border width in pixels
bg Normal background color
height Size of canvas in the Y dimension
width Size of the canvas in the X direction
cursor Cursor used in the canvas like arrow,
circle,dot
Syntax:
line=canvas.create_line(x0,y0,x1,y1,…………,xn,yn, options)
Example program:
top=Tk()
c=Canvas(top,bg="blue",height=250,width=300)
line=c.create_line(10,50,240,210,fill="red")
c.pack()
top.mainloop()
Output
2) create_polygon – Creates a polygon item that must have at least three vertices.
Syntax:
polygon=canvas.create_polygon(x0,y0,x1,y1,…………,xn,yn, options)
Example program:
top=Tk()
c=Canvas(top,bg="blue",height=250,width=300)
polygon=c.create_polygon(10,50,100,200,250,10,fill="red")
c.pack()
top.mainloop()
Output
3) create_oval – Creates a circle or an ellipse at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right corners of the bounding rectangle for the
oval.
Syntax:
oval=canvas.create_oval(x 0,y0,x1,y1,options)
Example Program:
top=Tk()
c=Canvas(top,bg="blue",height=250,width=300)
oval=c.create_oval(80,100,150,200,fill="red")
c.pack()
top.mainloop()
Output
4) create_arc - Creates an arc item, which can be a chord, a pieslice or a simple arc.
cord=10,50,240,210
arc=canvas.create_arc(coord,start=0,extent=180,fill=”blue”)
The start shows the start angle and extent shows the sweep angles in degrees.
Example Program:
top=Tk()
c=Canvas(top,bg="blue",height=250,width=300)
coord=10,50,240,210
arc=c.create_arc(coord,start=0,extent=180,fill="red")
c.pack()
top.mainloop()
Output
Syntax
filename=PhotoImage(file=filename.gif”)
image=canvas.create_image(x0,y 0, options,image=filename)
Example program:
top=Tk()
filename=PhotoImage(file="GLOBE.gif")
c=Canvas(top,bg="blue",height=400,width=400)
image=c.create_image(100,100,image=filename)
c.pack()
top.mainloop()
Output
Layout Managers
Layout managers are also known as geometry managers. tkinter posses three layout managers.
1. pack
2. grid
3. place
Using pack command, user can declare the positions of widgets relative to each other. The pack
command takes care of details. The pack command is easier to use. Pack manager is limited in
its possibilities compared to the grid, and place managers.
Example program:
root=Tk()
l=Label(root,text="Red Sun",bg="red",fg="white")
l.pack()
l=Label(root,text="Green Grass",bg="green",fg="white")
l.pack()
l=Label(root,text="Blue Sky",bg="blue",fg="white")
l.pack()
root.mainloop()
Output
a) fill
To make the widgets as wide as the parent widget, the option fill=X has to be used inside
pack().
Example:
root=Tk()
l=Label(root,text="Red Sun",bg="red",fg="white")
l.pack(fill=X)
l=Label(root,text="Green Grass",bg="green",fg="white")
l.pack(fill=X)
l=Label(root,text="Blue Sky",bg="blue",fg="white")
l.pack(fill=X)
root.mainloop()
Output
b) padding
root=Tk()
l=Label(root,text="Red Sun",bg="red",fg="white")
l.pack(fill=X,padx=20)
l=Label(root,text="Green Grass",bg="green",fg="white")
l.pack(fill=X,padx=20)
l=Label(root,text="Blue Sky",bg="blue",fg="white")
l.pack(fill=X,padx=20)
root.mainloop()
Output
Example program: (External padding in y direction (Vertically))
root=Tk()
l=Label(root,text="Red Sun",bg="red",fg="white")
l.pack(fill=X,pady=10)
l=Label(root,text="Green Grass",bg="green",fg="white")
l.pack(fill=X,pady=10)
l=Label(root,text="Blue Sky",bg="blue",fg="white")
l.pack(fill=X,pady=10)
root.mainloop()
Output
root=Tk()
l=Label(root,text="Red Sun",bg="red",fg="white")
l.pack(fill=X,ipadx=10)
l=Label(root,text="Green Grass",bg="green",fg="white")
l.pack(fill=X,ipadx=10)
l=Label(root,text="Blue Sky",bg="blue",fg="white")
l.pack(fill=X,ipadx=10)
root.mainloop()
Output
root=Tk()
l=Label(root,text="Red Sun",bg="red",fg="white")
l.pack(fill=X,ipady=10)
l=Label(root,text="Green Grass",bg="green",fg="white")
l.pack(fill=X,ipady=10)
l=Label(root,text="Blue Sky",bg="blue",fg="white")
l.pack(fill=X,ipady=10)
root.mainloop()
Output
c) side
To place label side by side, the option side of layout manager is used.
Example program:
root=Tk()
l=Label(root,text="Red Sun",bg="red",fg="white")
l.pack(padx=15,pady=10,side=LEFT)
l=Label(root,text="Green Grass",bg="green",fg="white")
l.pack(padx=15,pady=20,side=LEFT)
l=Label(root,text="Blue Sky",bg="blue",fg="white")
l.pack(padx=15,pady=20,side=LEFT)
root.mainloop()
Output
2) Place
The Place manager allows user to explicitly set the position and size of window. The position
can be set either in absolute terms or relative to another window. The place manager can be
accessed through the place method. It can be applied to all standard widgets.
Syntax:
widget.place(place_options)
a) anchor: The exact spot of widget. Options are N,E,S,W,NE,NW,SE,or SW. Default is NW
(The upper left corner of widget)
b) bordermode: INSIDE(the default) to indicate that other options refer to the parents
inside(ignoring the parent’s border);OUTSIDE otherwise
c) height,width : Height and width in pixels
d) 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.
e) 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.
f) x,y : Horizontal and vertical offset in pixels.
Example program:
def helloCallBack():
B=Button(top,text="Hello",command=helloCallBack)
B.pack()
B.place(bordermode=OUTSIDE,height=100,width=100)
top.mainloop()
Output
3) Grid
Grid was introduced as an alternative to pack. Grid is easier to learn, use and produce nice
layouts.
The Grid geometry manager places the widgets in a 2-dimensional table, which consists of
number of rows and columns. The position of widget is defined by a row and a column number.
Widgets with the same column number and different row numbers will be above or below each
other. Widgets with the same row number but different column numbers will be on the same
“line” and will be beside of each other. (i.e To the left or the right ). The size of grid doesn’t
have to be defined.
widget.grid(grid_options)
Example program:
root=Tk()
colors=['red','green','orange','white','yellow','blue']
r=0
for c in colors:
Label(text=c,width=15).grid(row=r,column=0)
Entry(bg=c,width=10).grid(row=r,column=1)
r=r+1
root.mainloop()
Output
Grid was used as an alternative to pack. Grid is easier to learn, use and produce nice layouts.
Grid is best choice for general use.
Place gives user complete control of positioning each element. But place is more complex than
pack and grid.