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

Unit 4 Python

Yes broh

Uploaded by

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

Unit 4 Python

Yes broh

Uploaded by

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

Unit 4

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.

The API includes following steps:

1. Importing the API module


2. Acquiring a connection with the database
3. Issuing SQL statements and stored procedures
4. Closing the connection

For connecting to MYSQL database, pymysql is needed. pymysql is an interface connecting


MySQL and Python. Before establishing connection between Python and MySQL, pymysql has
to be installed in machine.

CONNECTING TO A DATABASE

The steps for connecting to a database in Python are as follows:

1. Import pymysql module

Import pymysql module. This module’s method is used to communicate with the MySQL
database.

2. Create the connection object

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.

4. Execute the query

The execute() method run the SQL query and return the result.

5. Close connection objects

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.

Example program: (Connect MySQL database with Python)

import pymysql

# Open database connection

db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)

# Prepare a cursor object using cursor() method

cursor=db.cursor()

# execute SQL query using execute() method

cursor.execute(“SELECT VERSION()”)

# Fetch a single row using fetchone() method.

data=cursor.fetchone()

print(“Database version:”,data)

# disconnect from server

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

Basic Operations on Database (Create,Insert,Update,Delete)

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

# Open database connection

db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)

# Prepare a cursor object using cursor() method

cursor=db.cursor()

# Create table as per requirement

sql=”””CREATE TABLE DEPT(DEPTNO INT,DEPT_NAME CHAR(20),LOCATION CHAR(25))”””

cursor.execute(sql)

db.commit()

# disconnect from server

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

# open database connection

db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)

# Prepare a cursor object using cursor() method

cursor=db.cursor()

# Prepare SQL query to INSERT a record into the database

sql=”””INSERT INTO DEPT(DEPTNO,DEPT_NAME,LOCATION) VALUES(10,’Sales’,’Chennai’)”””

cursor.execute(sql)

db.commit()

# disconnect from server

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.

Example program (Update records in a table from Python)

import pymysql

# open database connection

db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)

# Prepare a cursor object using cursor() method

cursor=db.cursor()

# Prepare SQL query to UPDATE records into a table.

sql=”UPDATE DEPT SET LOCATION=’Delhi’ WHERE DEPT_NAME=’SALES’ “

cursor.execute(sql)

db.commit()

# disconnect from server

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

# open database connection

db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)

# Prepare a cursor object using cursor() method

cursor=db.cursor()

# Prepare SQL query to DELETE records from a table

sql=”DELETE FROM DEPT WHERE LOCATION=’Delhi’ “

cursor.execute(sql)

db.commit()

# disconnect from server

db.close()

……………………………………………………………………………………………………………………

The above example will delete all the records with location Delhi.

Fetching Data from a Database

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.

Following methods are used in READ operation

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

# open database connection

db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)

# Prepare a cursor object using cursor() method

cursor=db.cursor()

# Prepare SQL query

sql=”SELECT LOCATION FROM DEPT”

cursor.execute(sql)

# Fetches the next Record. In this case First record.

row=cursor.fetchone()

if row:

print(“Location:”,row[0])

# disconnect from server

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

# open database connection

db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)

# Prepare a cursor object using cursor() method

cursor=db.cursor()

# Prepare SQL query

sql=”SELECT LOCATION FROM DEPT”

cursor.execute(sql)

# Fetches all the records.

rows=cursor.fetchall()

for row in rows:

print(“Location:”,row[0])

# disconnect from server

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

# open database connection

db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)

# Prepare a cursor object using cursor() method

cursor=db.cursor()

# Prepare SQL query

sql=”SELECT LOCATION FROM DEPT”

cursor.execute(sql)

# Displays number of records

numrows=cursor.rowcount

print(“Number of Records:”,numrows.rowcount)

# disconnect from server

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)

Transaction is a mechanism to ensure data consistency. Transaction ensures 4 properties


generally referred to as ACID properties.

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.

Isolation : Isolation enable transactions to operate independently and transparent to each


other.

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

Example program for COMMIT and ROLLBACK

import pymysql

# open database connection

db=pymysql.connect(“localhost”,”user”,”pass”,”SAMPLE”)

# Prepare a cursor object using cursor() method

cursor=db.cursor()

# Prepare SQL query to INSERT a record into the database

sql=”””INSERT INTO DEPT(DEPTNO,DEPT_NAME,LOCATION) VALUES(10,’Sales’,’Chennai’)”””

cursor.execute(sql)

# Commit changes in the database

db.commit()

except:

# Rollback in case there is any error

db.rollback()

# disconnect from server

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.

GUI Programming using Tkinter

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.

Note: (Only for your understanding)

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.

Steps for creating GUI applications using Tkinter is as follows:

1. Import the Tkinter module.


2. Create the GUI application main window
3. Add one or more widgets to the GUI application
4. Enter the main event loop to take action against each event triggered by the user.

Tkinter Widgets (Label,Message,


Entry,Text,Button,tkMessagebox,RadioButton,Checkbutton,Listbox,Menu,Menubutton,Scale,
Scrollbar,Canvas)

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.

Example for widgets:

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.

Syntax for creating a label

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.

List of options and their descriptions:

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)

from tkinter import *

root=Tk()

label=Label(root,text="Welcome to Python Programming",font="Garamond")

label.pack()

root.mainloop()

Output

Note: (Only for your understanding)

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:

from tkinter import *

root=Tk()

msg=Message(root,text="Welcome to Python Programming",bg="yellow",font="Garamond")

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.

Syntax for creating entry widget

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.

List of options and their descriptions of Entry Widget

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:

from tkinter import *

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

Methods used along with entry widget

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.

The syntax for creating a text widget is as follows:

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.

List of options and their descriptions for Text Widget

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:

from tkinter import *

root=Tk()

t=Text(root,height=2,width=30)

t.pack()

t.insert(END,"Python Programming\n Let's a Try\n")

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.

Functions provided by tkMessageBox module are:

1. showinfo()
2. showwarning()
3. showerror()
4. askquestion()
5. askokcancel
6. askyesno()
7. askretryignore()

The syntax for creating this widget is as follows:

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.

Commonly used options are default and parent.

Example program:

from tkinter import *

from tkinter import messagebox

root=Tk()

def hello():

messagebox.showinfo("Python","Welcome to Python Programming")

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.

Syntax for Creating Button widget

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.

List of options and Descriptions for Button Widget

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

Commonly used methods for button widget are

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.

Example program (Button widget)

from tkinter import *

from tkinter import messagebox

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.

Syntax for creating a radio button is as follows:

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.

List of options and their descriptions for Radio Button

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.

Methods for radio button are as follows:

a) deselect() – Clears or turns off the radio button


b) flash() – flashes the radio button a few times between its active and normal colors.
c) invoke() – This method is called to get the same actions that would occur if the user
clicked on the radio button to change its state.
d) select() – Sets or turns on the radio button.

Example program:

from tkinter import *

root=Tk()

label=Label(root)

def sel():

selection="You selected " +str(var.get())

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.

Syntax for creating a checkbox:

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.

List of options and their descriptions for Checkbutton


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
offvalue A Checkbox’s associated control variable will be set to 0 when it is
cleared(off).
onvalue A Checkbox’s associated control variable will be set to 1 when it is set(on).
padx Space to leave to the left and right of the Checkbutton and text
pady Space to leave above and below the Checkbutton and text.
state The default state is NORMAL. The state is DISABLED, then Checkbutton
becomes unresponsive.
text The label displayed next to the Checkbutton.

Methods for checkbox widget are as follows:

a) deselect() – Clears or turns off the checkbox


b) flash() – flashes the checkbox a few times between its active and normal colors.
c) invoke() – This method is called to get the same actions that would occur if the user
clicked on the checkbox to change its state.
d) select() – Sets or turns on the checkbox.
e) toggle() – Clears the checkbox if set, sets it if cleared.

Example program:

from tkinter import *

root=Tk()

var1=IntVar()

var2=IntVar()
var3=IntVar()

var1.set(0)

var2.set(0)

var3.set(0)

def sel():

if var1.get()==1:

label1=Label(text="You selected windows").pack()

if var2.get()==1:

label2=Label(text="You selected solaris").pack()

if var3.get()==1:

label3=Label(text="You selected Linux").pack()

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.

Syntax for creating a listbox:

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.

List of options and their Descriptions for Listbox

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

Commonly used methods for Listbox

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:

from tkinter import *

master=Tk()

listbox=Listbox(master)

listbox.pack()

for item in ["apple","orange","pear","grapes"]:

listbox.insert(END,item)

master.mainloop()
Output

Menu Widget

Menu widget can be used to create different kind of menus.

Three types of menus can be created:

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.

The syntax for creating a menubutton is

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.

List of options and their description for Menubutton

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

List of Methods and their description for Menu widget

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:

from tkinter import *

root=Tk()

def hello():

print("hello!")

# create a toplevel menu


menubar = Menu(root)

menubar.add_command(label="Hello!", command=hello)

menubar.add_command(label="Quit!", command=root.quit)

# display the menu

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.

Syntax for creating a menubutton is as follows:

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.

List of options and their descriptions for Menubutton

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:

from tkinter import*

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.

Syntax for creating scrollbar is as follows:

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.

List of options and their descriptions for Scrollbar

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:

from tkinter import *

root=Tk()

scrollbar=Scrollbar(root)

scrollbar.pack(side=RIGHT,fill=Y)

mylist=Listbox(root,yscrollcommand=scrollbar.set)

for line in range(100):

mylist.insert(END,"This is line number"+str(line))

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.

The syntax for creating a scale widget is:

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.

List of options and their description for Scale

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.

The get() method returns the current value of the scale.

The method set(value) sets the scales value.

Example program:

from tkinter import*

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

Note: when Show button is pressed, the value 27,12 is displayed.

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.

The syntax for creating Canvas widget is as follows:

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.

List of options and their descriptions for Canvas

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

Following methods are used for drawing on a Canvas

1) create_line – Creates a line item.

Syntax:

line=canvas.create_line(x0,y0,x1,y1,…………,xn,yn, options)

Example program:

from tkinter import*

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:

from tkinter import*

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:

from tkinter import*

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:

from tkinter import*

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

5) create_image - Creates an image item which can be an instance of PhotoImage class.

Syntax

filename=PhotoImage(file=filename.gif”)
image=canvas.create_image(x0,y 0, options,image=filename)

Example program:

from tkinter import*

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

Layout managers perform various functions.

 They arrange widgets on the screen.


 Register widgets with the underlying windowing system
 Manages the display of widgets on the screen.
1. Pack

Pack is the easiest to use of the three geometry managers of tkinter.

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:

from tkinter import *

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:

from tkinter import *

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

The pack() manager knows four padding options.

1. External padding in x direction (Horizontally)


2. External padding in y direction (Vertically)
3. Internal padding in x direction (Horizontally)
4. Internal padding in y direction (Vertically)

Example program: (External padding in x direction (Horizontally))

from tkinter import *

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

from tkinter import *

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

Example program: (Internal padding in x direction (Horizontally))


from tkinter import *

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

Example program: (Internal padding in y direction (Vertically))

from tkinter import *

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:

from tkinter import *

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)

The options for place geometry managers are :

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:

from tkinter import *

from tkinter import messagebox


top=Tk()

def helloCallBack():

messagebox.showinfo("Hello Python","Hello World")

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.

The grid has the following syntax:

widget.grid(grid_options)

The lists of possible options are:

a) column: The column to put widget in. Default is 0 (leftmost column)


b) columnspan: Shows how many columns widget occupies. Default is 1.
c) ipadx, ipady: Shows how many pixels to pad widget horizontally and vertically, inside
widget’s borders.
d) padx, pady : Shows how many pixels to pad widget, horizontally and vertically.
e) row: The row to put widget in. Default is the first row that is still empty.
f) rowspan: Shows how many rows widget occupies. Default is 1.

Example program:

from tkinter import*

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

Comparison between grid,pack and place

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.

You might also like