Python II notes
Python II notes
[Date] 1
Removing Elements from the Array
Elements can be removed from the Python array by using built-in remove() function but
an Error arises if element doesn’t exist in the set. remove() method only removes one
element at a time,
to remove range of elements, iterator is used. pop() function can also be used to remove
and return an element from the array, by default it removes only the last element of the
array, to remove element from a specific position of the array, index of the element is
passed as an argument to the pop() method.
import array
arr = array.array('i', [1, 2, 3, 1, 5])
print("The new created array is : ", end="")
for i in range(0, 5):
print(arr[i], end=" ")
print("\r")
print("The popped element is : ", end="")
print(arr.pop(2))
print("The array after popping is : ", end="")
for i in range(0, 4):
print(arr[i], end=" ")
print("\r")
arr.remove(1)
print("The array after removing is : ", end="")
for i in range(0, 3):
print(arr[i], end=" ")
[Date] 2
It adds powerful data structures to Python that guarantee efficient calculations with arrays
and matrices and it supplies an enormous library of high-level mathematical functions
that operate on these arrays and matrices.
[Date] 3
Why use NumPy?
NumPy arrays are faster and more compact than Python lists.
An array consumes less memory and is convenient to use.
NumPy uses much less memory to store data and it provides a mechanism of
specifying the data types.
This allows the code to be optimized even further.
What is an array?
An array is a central data structure of the NumPy library.
An array is a grid of values and
it contains information about the raw data,
how to locate an element, and
ow to interpret an element.
It has a grid of elements that can be indexed in various ways.
The elements are all of the same type, referred to as the array dtype.
An array can be indexed
by a tuple of nonnegative integers,
by booleans,
by another array, or by integers.
The rank of the array is the number of dimensions.
The shape of the array is a tuple of integers giving the size of the array along each
dimension.
The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very
important.
[Date] 4
1. NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
2. This behavior is called locality of reference in computer science.
3. This is the main reason why NumPy is faster than lists. Also it is optimized to work
with latest CPU architectures.
4. Which Language is NumPy written in?
5. NumPy is a Python library and is written partially in Python, but most of the parts
that require fast computation are written in C or C++.
Where is the NumPy Codebase?
The source code for NumPy is located at this github repository
https://github.com/numpy/numpy
github: enables many people to work on the same codebase.
Printing an array
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)\
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
We can create a NumPy ndarray object by using the array() function.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Arrays in Phython
To create an ndarray, we can pass a list, tuple or any array-like object into the array()
method, and it will be converted into an ndarray: an array referred to as a “ndarray,”
which is shorthand for
“N-dimensional array.”
An N-dimensional array is simply an array with any number of dimensions. We can have
1-D, or one-dimensional array,
2-D, or two-dimensional array, and so on.
The NumPy ndarray class is used to represent both matrices and vectors.
A vector is an array with a single dimension (there’s no difference between row and
column vectors),
while a matrix refers to an array with two dimensions.
For 3-D or higher dimensional arrays, the term tensor is also commonly used.
In NumPy, dimensions are called axes. This means that if you have a 2D array that looks
like this:
[[0., 0., 0.],
[1., 1., 1.]]
array has 2 axes.
The first axis has a length of 2 and
the second axis has a length of 3.
Operations using NumPy:
[Date] 5
• Using NumPy, a developer can perform the following operations −
• Mathematical and logical operations on arrays.
• Fourier transforms and routines for shape manipulation.
• Operations related to linear algebra. NumPy has in-built functions for linear algebra
and random number generation.
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example
Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array. These
are the most common and basic arrays.
Example : Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array. These are often used to
represent matrix or 2nd order tensors. NumPy has a whole sub module dedicated towards
matrix operations called numpy.mat
Example: :reate a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.These are often
used to represent a 3rd order tensor.
Example : Create a 3-D array with two 2-D arrays, both containing two arrays with the
values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
[Date] 6
# Printing type of arr object
print("Array is of type: ", type(arr))
a = np.array([1, 2, 5, 3])
# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
[Date] 7
print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)
Unary operators: Many unary operations are provided as a method of ndarray class.
This includes sum, min, max, etc. These functions can also be applied row-wise or
column-wise by setting an axis parameter.
# Python program to demonstrate
# unary operators in numpy
import numpy as np
PANDAS
Pandas is a Python library used for working with data sets. It has functions for analyzing,
cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and
was created by Wes McKinney in 2008.
Pandas is an open-source library that is made mainly for working with relational or
labeled data both easily and intuitively. It provides various data structures and operations
for manipulating numerical data and time series. This library is built on top of the NumPy
library.
[Date] 8
Why Use Pandas?
Pandas allows us to analyze big data and make conclusions based on statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science.
[Date] 9
info = np.array(['P','a','n','d','a','s'])
a = pd.Series(info)
print(a)
import pandas as pd
import numpy as np
# simple array
data = np.array(['g', 'e', 'e', 'k', 's'])
ser = pd.Series(data)
DataFrame
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular
data structure with labeled axes (rows and columns). A Data frame is a two-dimensional
data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas
DataFrame consists of three principal components, the data, rows, and columns.
[Date] 10
Creating a DataFrame:
In the real world, a Pandas DataFrame will be created by loading the datasets from
existing storage, storage can be SQL Database, CSV file, an Excel file. Pandas
DataFrame can be created from the lists, dictionary, and from a list of dictionaries, etc.
Create a DataFrame using List:
We can easily create a DataFrame in Pandas using list.
import pandas as pd
# a list of strings
x = ['Python', 'Pandas']
import pandas as pd
# Calling DataFrame constructor
df = pd.DataFrame()
print(df)
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
[Date] 11
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)
print(df)
Locate Row
As you can see from the result above, the DataFrame is like a table with rows and
columns.
Pandas use the loc attribute to return one or more specified row(s)
Example
Return row 0:
#refer to the row index:
print(df.loc[0])
[Date] 12
Example
Return row 0 and 1:
#use a list of indexes:
print(df.loc[[0, 1]])
Named Indexes
With the index argument, you can name your own indexes.
Add a list of names to give each row a name:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
df = pd.DataFrame(data, index = ["day1", "day2", "day3"])
print(df)
df = pd.read_csv('data.csv')
print(df)
If you have a large DataFrame with many rows, Pandas will only return the first 5 rows,
and the last 5 rows
Increase the maximum number of rows to display the entire DataFrame:
[Date] 13
import pandas as pd
pd.options.display.max_rows = 9999
df = pd.read_csv('data.csv')
print(df)
Print(pdf)
[Date] 14
skiprows help to skip some rows in CSV, i.e, here you will observe that the upper row
and the last row from the original CSV data have been skipped.
pd.read_csv("example1.csv", skiprows = [1,12])
df.tail(2)
df.head(2)
Data Visualization
Data visualization is the practice of translating information into a visual context, such as a
map or graph, to make data easier for the human brain to understand and pull insights
from. The main goal of data visualization is to make it easier to identify patterns, trends
and outliers in large data sets. The term is often used interchangeably with others,
including information graphics, information visualization and statistical graphics.
an increased understanding of the next steps that must be taken to improve the
organization;
an improved ability to maintain the audience's interest with information they can
understand;
an easy distribution of information that increases the opportunity to share insights with
everyone involved;
eliminate the need for data scientists since data is more accessible and understandable;
and
an increased ability to act on findings quickly and, therefore, achieve success with greater
speed and less mistakes.
Matplotlib
Matplotlib is a low level graph plotting library in python that serves as a visualization
utility.
[Date] 15
Matplotlib was created by John D. Hunter.
Matplotlib is mostly written in python, a few segments are written in C, Objective-C and
Javascript for Platform compatibility.
Version
import matplotlib
print(matplotlib.__version__)
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported
under the plt alias:
Or
MATPLOTLIB
import matplotlib.pyplot as plt
import numpy as np
x1=np.linspace(0,5,10)
y1=x1**2
plt.plot(x1,y1)
plt.title("days squared chart")
plt.xlabel("days")
plt.ylabel("days squared")
x=[5,2,9,4,7]
[Date] 16
y=[10,6,8,4,2]
plt.bar(x,y)
x=[5,2,9,4,7]
y=[10,6,8,4,2]
plt.scatter(x,y)
x=[5,2,9,4,7]
y=[10,6,8,4,2]
plt.hist(y)
[Date] 17
import pandas as pd
df=pd.DataFrame(np.random.rand(10,5), columns=['A','B','C','D','E'])
df.plot.area()
plt.show()
days=[1,2,3,4,5]
sleeping=[7,8,6,11,7]
eating=[2,3,4,3,2]
working=[7,8,7,2,2]
playing=[7,8,7,8,3]
plt.plot([1,2,3,4,5],[7,8,6,11,7], color='m', label='sleeping', linewidth=5)
plt.plot([1,2,3,4,5],[2,3,4,3,2], color='r', label='eating', linewidth=5)
plt.plot([1,2,3,4,5],[7,8,7,2,2], color='c', label='playing', linewidth=5)
#box plot
df=pd.DataFrame(np.random.rand(10,5),columns=['A','B','C','D','E'])
df.plot.box()
plt.show
[Date] 18
SQLite,
The Python programming language has powerful features for database programming.
Python is a high-level, general-purpose, and very popular programming language.
Basically, it was designed with an emphasis on code readability, and programmers can
express their concepts in fewer lines of code.
We can also use Python with SQL.
The diagram given below illustrates how a connection request is sent to MySQL
connector Python, how it gets accepted from the database and how the cursor is executed
with result data.
Python supports various databases like SQLite, MySQL, Oracle, Sybase, PostgreSQL,
etc.
[Date] 19
2. serverless, and
3. self-contained,
4. high-reliable.
SQLite is the most commonly used database engine in the test environment (Refer to
SQLite Home page).
Connect To Database
Following Python code shows how to connect to an existing database. If the database
does not exist, then it will be created and finally a database object will be returned.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
[Date] 20
Create a Table
Following Python program will be used to create a table in the previously created
database.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute('''CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";
conn.close()
When the above program is executed, it will create the COMPANY table in your test.db
and it will display the following messages −
Opened database successfully
Table created successfully
Insert Operation
Following Python program shows how to create records in the COMPANY table created
in the above example.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");
conn.commit()
print "Records created successfully";
conn.close()
When the above program is executed, it will create the given records in the COMPANY
table and it will display the following two lines −
Opened database successfully
Records created successfully
Select Operation
Following Python program shows how to fetch and display records from the COMPANY
table created in the above example.
[Date] 21
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
When the above program is executed, it will produce the following result
.
Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
[Date] 22
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000.0
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
Delete Operation
Following Python code shows how to use DELETE statement to delete any record and
then fetch and display the remaining records from the COMPANY table.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("DELETE from COMPANY where ID = 2;")
conn.commit()
print "Total number of rows deleted :", conn.total_changes
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
[Date] 23
print "Operation done successfully";
conn.close()
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Dropping a table
• import sqlite3
• #Connecting to sqlite
• conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor()
method cursor = conn.cursor()
• #Doping EMPLOYEE table if already exists cursor.execute("DROP TABLE emp")
print("Table dropped... ")
• #Commit your changes in the database conn.commit()
• #Closing the connection
conn.close()
TKinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all
the GUI methods, tkinter is the most commonly used method. It is a standard Python
interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and
easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.
[Date] 24
Apply the event Trigger on the widgets.
top = Tkinter.Tk()
There are two main methods used which the user needs to remember while creating
the Python application with GUI.
2. mainloop():
There is a method known by the name mainloop() is used when your application is ready
to run. mainloop() is an infinite loop used to run the application, wait for an event to
occur and process the event as long as the window is not closed.
Layout Management
tkinter also offers access to the geometric configuration of the widgets which can
organize the widgets in the parent windows. There are mainly three geometry manager or
layout manager classes class.
pack() method:It organizes the widgets in blocks before placing in the parent widget.
grid() method:It organizes the widgets in grid (table-like structure) before placing in the
parent widget.
[Date] 25
place() method:It organizes the widgets by placing them on specific positions directed
by the programmer.
This geometry manager organizes widgets in blocks before placing them in the parent
widget.
Syntax
widget.pack( pack_options )
expand − When set to true, widget expands to fill any space not otherwise used in
widget's parent.
fill − Determines whether widget fills any extra space allocated to it by the packer, or
keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill
only vertically), or BOTH (fill both horizontally and vertically).
side − Determines which side of the parent widget packs against: TOP (default),
BOTTOM, LEFT, or RIGHT.
Grid()
This geometry manager organizes widgets in a table-like structure in the parent widget.
Syntax
[Date] 26
columnspan − How many columns widgetoccupies; default 1.
ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside
widget's borders.
padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's
borders.
row − The row to put widget in; default the first row that is still empty.
sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is
centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W,
NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to
which widget sticks.
Place()
This
geometry manager organizes widgets by placing them in a specific position in the parent
widget.
Syntax
widget.place( place_options )
anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW,
SE, or SW, compass directions indicating the corners and sides of widget; default is NW
(the upper left corner of widget)
[Date] 27
bordermode − INSIDE (the default) to indicate that other options refer to the parent's
inside (ignoring the parent's border); OUTSIDE otherwise.
relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the
height and width of the parent widget.
relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of
the height and width of the parent widget.
Widgets
w=Button(master, option=value)
There are number of options which are used to change the format of the Buttons. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.
activebackground: to set the background color when button is under the cursor.
activeforeground: to set the foreground color when button is under the cursor.
[Date] 28
image: to set the image on the button.
Sample Program
import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button.pack()
r.mainloop()
Canvas: It is used to draw pictures and other complex layout like graphics, text and
widgets.
The general syntax is:
w = Canvas(master, option=value)
master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
[Date] 29
highlightcolor: to set the color shown in the focus highlight.
Sample Program
master = Tk()
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()
w = CheckButton(master, option=value)
There are number of options which are used to change the format of this widget.
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
activebackground: to set the background color when widget is under the cursor.
activeforeground: to set the foreground color when widget is under the cursor.
[Date] 30
command: to call a function.
Sample Program
master = Tk()
var1 = IntVar()
var2 = IntVar()
mainloop()
Entry:It is used to input the single line text entry from the user.. For multi-line text input,
Text widget is used.
The general syntax is:w=Entry(master, option=value) master is the parameter used to
represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
[Date] 31
Sample Program
master = Tk()
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop()
Frame: It acts as a container to hold the widgets. It is used for grouping and organizing
the widgets.
w = Frame(master, option=value)
master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
highlightcolor: To set the color of the focus highlight when widget has to be focused.
[Date] 32
Sample Program
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
root.mainloop()
Label: It refers to the display box where you can put any text or image which can be
updated any time as per the code.
The general syntax is:
w=Label(master, option=value)
master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.
[Date] 33
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
Sample Program
root = Tk()
w = Label(root, text='GeeksForGeeks.org!')
w.pack()
root.mainloop()
7.Listbox: It offers a list to the user from which the user can accept any number of
options.
The general syntax is:
w = Listbox(master, option=value)
master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
highlightcolor: To set the color of the focus highlight when widget has to be focused.
[Date] 34
bg: to set the normal background color.
Sample Program
top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.pack()
top.mainloop()
MenuButton: It is a part of top-down menu which stays on the window all the time.
Every menubutton has its own functionality.
w = MenuButton(master, option=value)
master is the parameter used to represent the parent window.There are number of options
which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
[Date] 35
activebackground: To set the background when mouse is over the widget.
cursor: To appear the cursor when the mouse over the menubutton.
highlightcolor: To set the color of the focus highlight when widget has to be focused.
Sample Program
top = Tk()
mb.grid()
mb["menu"] = mb.menu
cVar = IntVar()
aVar = IntVar()
mb.pack()
top.mainloop()
[Date] 36
Menu: It is used to create all kinds of menus used by the application.
The general syntax is:
w = Menu(master, option=value)
master is the parameter used to represent the parent window.There are number of options
which are used to change the format of this widget.
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
activebackground: to set the background color when widget is under the cursor.
activeforeground: to set the foreground color when widget is under the cursor.
Sample Program
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
[Date] 37
mainloop()
Message: It refers to the multi-line and non-editable text. It works same as that of Label.
The general syntax is:
w = Message(master, option=value)
master is the parameter used to represent the parent window. There are number of options
which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
Sample Program
main = Tk()
messageVar.config(bg='lightgreen')
messageVar.pack( )
main.mainloop( )
[Date] 38
RadioButton: It is used to offer multi-choice option to the user. It offers several options
to the user and the user has to choose one option.
The general syntax is:
w = RadioButton(master, option=value)
There are number of options which are used to change the format of this widget.
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
activebackground: to set the background color when widget is under the cursor.
activeforeground: to set the foreground color when widget is under the cursor.
Sample Program
root = Tk()
v = IntVar()
mainloop()
[Date] 39
Scale: It is used to provide a graphical slider that allows to select any value from that
scale. The general syntax is:
w = Scale(master, option=value)
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
cursor: To change the cursor pattern when the mouse is over the widget.
activebackground: To set the background of the widget when mouse is over the widget.
to: To set the value of the other end of the scale range.
Scrollbar: It refers to the slide controller which will be used to implement listed widgets.
The general syntax is:
w = Scrollbar(master, option=value)
Number of options can be passed as parameters separated by commas. Some of them are
listed below.
[Date] 40
cursor: To appear the cursor when the mouse over the menubutton.
Text: To edit a multi-line text and format the way it has to be displayed.
The general syntax is:
w =Text(master, option=value) There are number of options which are used to change the
format of the text. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
highlightcolor: To set the color of the focus highlight when widget has to be focused.
TopLevel: This widget is directly controlled by the window manager. It don’t need any
parent window to work on.The general syntax is:
w = TopLevel(master, option=value)
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.
cursor: To appear the cursor when the mouse over the menubutton.
SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed
value of numbers.The general syntax is:
[Date] 41
bd: to set the size of border around the indicator.
cursor: To appear the cursor when the mouse over the menubutton.
w = PannedWindow(master, option=value)
cursor: To appear the cursor when the mouse over the menubutton.
[Date] 42