Modules and Packages
In Python programming, structuring code for reusability, scalability, and maintainability
is essential. For this the concepts of modules, packages, and libraries are used.
Module: A single Python file containing code, such as functions, classes, or variables,
designed to be imported and reused.
Package: A collection of Python modules organized within a directory that contains
an __init__.py file, enabling hierarchical structuring of related modules.
Library: A broader term referring to a collection of modules and packages bundled
together to provide specific functionality or a set of features.
Modules
A module in Python is fundamentally a single .py file that contains Python code
(functions, classes, and variables) that can be imported and reused in other Python
programs.
Python's standard library is composed primarily of modules, such as math, random,
and datetime.
Importing a module is done via the import statement, e.g., import math.
1. Create a Module File-
First, you create a Python file that will serve as your module. Let's create a file
named [Link] with the following content:
[Link]
def f1(name):
return "Hello "+name
def f2(name):
return "Goodbye "+name
color = "Blue"
2. Use the Module in Another Program
Next, you can create another Python script in the same directory (e.g., [Link]) and
import the functions and variables from the test module to use them:
[Link]
import test
# Use the functions from the module
msg1 = test.f1("Amit")
msg2 = test.f2("Sumit")
print(msg1)
print(msg2)
# Access a variable from the module
print("My favorite color is:", [Link])
Alternative Import Syntax: You can also import specific items directly.
[Link]
from test import f1, color
msg1 = f1("Amit")
print(msg1)
print("My favorite color is:", color)
Variations of the import statement:
In Python, import statements are used to bring code from other modules or packages into
the current script's namespace, allowing for code reuse and organization. There are
several variations of the import statement:
import module_name
It brings the entire module into your program, You must use dot notation
(e.g., module_name.function_name()) to access the functions, classes, or variables
within the module.
Ex: import math
from module_name import item1, item2, ...
This syntax allows you to import specific items (functions, classes, or variables)
directly into the current program. You can then use the item's name without the
module prefix. Useful when you only need a few specific items and want to avoid the
longer module_name. prefix.
Ex: from math import sqrt, pi
import module_name as alias
This method allows you to give the imported module an alternative, shorter name
(an alias) within your script.
Ex: import math as m
from module_name import *
This imports all public names (functions, classes, variables) from a module into the
current Program.
Ex: from math import *
Package
A python package is a collection of modules. Modules that are related to each other
are generally put in the same package.
When a module from an external package is required in a program, that package can
be imported and its modules can be put to use.
While working on big projects, we have to deal with a large amount of code, and
writing everything together in the same file will make our code look messy. Instead, we
can separate our code into multiple files by keeping the related code together in
packages.
Note: A directory must contain a file named __init__.py in order for Python to
consider it as a package. This file can be left empty but we generally place the
initialization code for that package in this file.
Creating Package:
Let’s create a package in Python named mypckage that will contain two modules mod1
and mod2. To create this module follow the below steps:
Create a folder named mypckage.
Inside this folder create an empty Python file i.e. __init__.py
Then create two modules (.py files) mod1 and mod2 in this folder.
[Link]
def product(x, y):
print(x*y)
[Link]
def sum(x, y):
return x+y
We can import these Python modules using the following statement and the dot(.)
operator.
Syntax:
import mypackage.mod1, mypackage.mod2
or from mypackage import mod1, mod2
from mypackage import mod1, mod2
[Link](2,3)
s = [Link](2,3)
print(s)
Qu. WAP for following Package Structure, and use the content of
“mypackage” inside “[Link]” program.
Introduction to NumPy
NumPy is a general-purpose array-processing package, It is short for "Numerical
Python". It is the fundamental package for scientific computing with Python.
NumPy aims to provide a multidimensional homogeneous array object that
is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
Why is NumPy Faster Than Lists?
NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
This behavior is called locality of reference in computer science.
Also it is optimized to work with latest CPU architectures.
Installation of NumPy:
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy. Install it using this command:
C:\Users\> pip install numpy
Once NumPy is installed, import it in your applications by adding
the import keyword:
import numpy
Create a NumPy ndarray Object:
The array object in NumPy is called ndarray. We can create a
NumPy ndarray object by using the array() function.
Example:
import numpy
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Output: [1 2 3 4 5]
<class '[Link]'>
NumPy is usually imported under the np alias. Create an alias with the as keyword
while importing:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
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.
A dimension in arrays is one level of array depth (nested arrays). Nested
array: are arrays that have arrays as their elements.
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D
array.
arr = [Link](42)
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
arr = [Link]([1, 2, 3, 4, 5])
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.
arr = [Link]([[1, 2, 3], [4, 5, 6]])
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
Attributes of ndarray
1. ndim (Number of Dimensions):
The ndim attribute returns the number of dimensions (axes) of the NumPy array.
Ex:
import numpy as np
arr1 = [Link]([1, 2, 3, 4])
print([Link]) # Output: 1
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])
print([Link]) # Output: 2
arr3 = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print([Link]) # Output: 3
2. size (Total Number of Elements)
The size attribute gives the total number of elements in the array, regardless of its dimensions.
Ex:
arr = [Link]([1, 2, 3, 4, 5])
print([Link]) # Output: 5
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print([Link]) # Output: 6
This is a 2 × 3 array, meaning it has 6 elements.
3. dtype (Data Type of Elements)
The dtype attribute tells us the type of elements in the array.
Ex:
arr = [Link]([1, 2, 3])
print([Link]) # Output: int32 or int64 (depends on system)
arr = [Link]([1.5, 2.7, 3.9])
print([Link]) # Output: float64
arr = [Link]([1, 2, 3], dtype=np.float32)
print([Link]) # Output: float32
Here, we explicitly set the data type to float32.
4. shape (Dimensions of the Array)
The shape attribute returns the dimensions of the array as a tuple.
arr = [Link]([1, 2, 3, 4])
print([Link]) # Output: (4,)
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print([Link]) # Output: (2, 3)
arr = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print([Link]) # Output: (2, 2, 2)
5. itemsize (Size of Each Element in Bytes)
The itemsize attribute returns the memory size of a single array element.
arr = [Link]([1, 2, 3])
print([Link]) # Output: 8 (for int64) or 4 (for int32)
arr = [Link]([1.5, 2.7, 3.9])
print([Link]) # Output: 8 (for float64)
6. linspace() (Evenly Spaced Values Over an Interval)
The linspace() function generates evenly spaced numbers over a given interval.
Example
arr = [Link](2, 8, 4)
print(arr) # Output: [2. 4. 6. 8.]
arr = [Link](0, 20, 7)
print(arr) # Output: [ 0. 3.33 6.67 10. 13.33 16.67 20. ]
7. arange() (Generating an Array with Steps)
The arange() function is similar to range(), but it returns a NumPy array.
Example
arr = [Link](1, 10, 2)
print(arr) # Output: [1 3 5 7 9]
arr = [Link](0, 5, 0.5)
print(arr) # Output: [0. 0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5]
Summary Table
Attribute/Function Description Example Output
ndim Number of dimensions 2 for a 2D array
size Total number of elements 6 for [[1,2,3], [4,5,6]]
dtype Data type of elements int32, float64
shape Tuple of array dimensions (2, 3) for a 2×3 matrix
itemsize Size of each element in bytes 8 for float64
linspace() Evenly spaced values [1. 3.25 5.5 7.75 10.]
arange() Generates array with step [1 3 5 7 9]
Access Array Elements:
import numpy as np
arr = [Link]([1, 2, 3, 4])
print(arr[0])
print(arr[2] + arr[3])
arr1 = [Link]([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr1[0, 1])
print('5th element on 2nd row: ', arr1[1, 4])
arr2 = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9],[10, 11, 12]]])
print(arr2[0, 1, 2])
Output: 1
7
2nd element on 1st row: 2
5th element on 2nd row: 10
6
import numpy as np
data1 = [6, 7.5, 8, 0, 1]
arr1 = [Link](data1)
print(arr1) # [6. 7.5 8. 0. 1. ]
print([Link]) # float64
print([Link]) # (5,)
print([Link]) #1
import numpy as np
data2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
arr2 = [Link](data2)
print([Link]) #2
print([Link]) # (2, 4)
import numpy as np
a= [Link]([1,2,3])
print([Link]()) # 1
print([Link]()) # 3
print([Link]()) # 6
import numpy as np
a= [Link]([(1, 2, 3), (3, 4, 5)])
# For column wise sum (axis=0)
print([Link](axis=0)) # [4 6 8]
# For row wise sum (axis=1)
print([Link](axis=1)) # [ 6 12]
Introduction to Matplotlib
Data Visualization:
Data visualization is the graphical representation of information and data. Can
be achieved using visual elements like figures, charts, graphs, maps, and more.
Data visualization tools provide a way to present these figures and graphs. Often, it
is essential to analyze massive amounts of information and make data-driven
decisions.
Converting complex data into an easy to understand representation.
Matplotlib:
Matplotlib is one of the most powerful tools for data visualization in Python. It is an
incredibly powerful 2-D plotting library in python.
Matplotlib is open source and we can use it freely. It is easy to use and provides a
huge number of examples for tackling unique problems.
If you have Python and PIP already installed on a system, then installation of
Matplotlib is very easy. Install it using following command:
C:\Users\>pip install matplotlib
Once Matplotlib is installed, import it in your applications by adding
the import module statement:
import matplotlib
Checking Matplotlib Version:
print(matplotlib.__version__)
Pyplot:
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias:
import [Link] as plt
Matplotlib comes with a wide variety of plots. Some of the sample
plots are.
Line plot
Histogram
Bar Chart
Scatter plot
Pie charts
Whenever you plot with matplotlib, the two main code lines should
be considered:
Type of graph (this is where you define a bar chart, line chart,
etc.)
Show the graph (this is to display the graph )
Line Plots:
A line plot shows the relationship between the x and y-axis.
The plot() function in the Matplotlib library’s Pyplot module
creates a 2D hexagonal plot of x and y coordinates. plot() will take
various arguments like-
plot(x, y, **kwargs)
By default, the plot() function draws a line from point to point.
The function takes parameters for specifying points in the
diagram.
Parameter 1 is an array containing the points on the x-axis.
Parameter 2 is an array containing the points on the y-axis.
If we need to plot a line from (1, 3) to (8, 10), we have to pass
two arrays [1, 8] and [3, 10] to the plot function.
import [Link] as plt
import numpy as np
xpoints = [Link]([1, 8])
ypoints = [Link]([3, 10])
[Link](xpoints, ypoints)
[Link]()
Ex:
import [Link] as plt
import numpy as np
xpoints = [Link]([1, 3, 5, 1])
ypoints = [Link]([3, 3, 1, 1])
[Link](xpoints, ypoints)
[Link]()
To plot the markers, you can use shortcut string notation parameter
marker='o', which means 'rings'.
import [Link] as plt
import numpy as np
xpoints = [Link]([1, 8])
ypoints = [Link]([3, 10])
[Link](xpoints, ypoints, marker=’o’)
[Link]()
To plot only the markers, you can use shortcut string
notation parameter 'o', which means 'rings'.
import [Link] as plt
import numpy as np
xpoints = [Link]([1, 8])
ypoints = [Link]([3, 10])
[Link](xpoints, ypoints, ‘o’)
[Link]()
To add labels in graph you can use methods-
[Link]("X-axis")
[Link]("Y-axis")
Bar chart:
A bar plot or bar chart is a graph that represents the category of
data with rectangular bars. It can be created using
the bar() method.
import [Link] as plt
#Create data for plotting
values = [5, 6, 3, 7, 2]
names = ["A", "B", "C", "D", "E"]
[Link](names, values, color="green")
[Link]()
With Pyplot, you can use the pie() function to draw pie charts
including labels, starting angle etc. A title is added
with plt. title(), and plt. show() displays the resulting pie chart,
visualizing the proportional distribution of the specified
categories.
import [Link] as plt
label = ['First', 'Second', 'Third']
sizes = [35, 35, 30]
[Link](sizes, labels=label, startangle=90)
[Link]('Pie Chart Example')
[Link]()
Introduction to Pandas
Pandas is a powerful and versatile library that simplifies tasks of
data manipulation and used for working with data sets in Python .
Pandas is built on top of the NumPy library and is particularly
well-suited for working with tabular data, such as spreadsheets or
SQL tables.
Its an essential tool for data analysts, scientists, and engineers
working with structured data in Python.
It has functions for analyzing, cleaning, exploring, and
manipulating data.
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.
Installing Pandas:
We need to install pandas in our system using the pip command.
C:\Users\>pip install pandas
Importing Pandas:
After the pandas have been installed into the system, you need to
import the library, it is usually imported under the pd alias:
import pandas as pd
Pandas Data Structures:
Pandas generally provide two data structures for manipulating data,
they are:
Series
DataFrame
Pandas Series
A Pandas Series is a one-dimensional labeled array capable of
holding data of any type (integer, string, float, python objects,
etc). The axis labels are collectively called indexes.
Pandas Series is nothing but a column in an Excel sheet. Labels
need not be unique but must be a hashable type.
Pandas Series can be created by loading the datasets from SQL
Database, CSV file, or an Excel file. It can also be created from
lists, dictionaries, and from scalar values, etc.
EXAMPLE:
import pandas as pd
import numpy as np
# Creating empty series
ser = [Link]()
print("Pandas Series: ", ser)
# simple array
data = [Link](['g', 'e', 'e', 'k', 's'])
ser = [Link](data)
print("Pandas Series:\n", ser)
OUTPUT:
Pandas Series: Series([], dtype: object)
Pandas Series:
0 g
1 e
2 e
3 k
4 s
dtype: object
Create Labels
With the index argument, you can name your own labels.
Example:
Create your own labels:
import pandas as pd
a = [1, 7, 2]
var = [Link](a, index = ["x", "y", "z"])
print(var)
OUTPUT:
x 1
y 7
z 2
dtype: int64
DataFrame
Pandas DataFrame is a two-dimensional data structure with
labeled axes (rows and columns).
Pandas DataFrame can be created by loading the datasets from SQL
Database, CSV file, or an Excel file. Pandas DataFrame can be
created from lists, dictionaries, and from a list of dictionaries,
etc.
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
#load data into a DataFrame object:
df = [Link](data)
print(df)
OUTPUT:
calories duration
0 420 50
1 380 40
2 390 45
Named Indexes:
With the index argument, you can name your own indexes.
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
df = [Link](data, index = ["day1", "day2", "day3"])
print(df)
OUTPUT:
calories duration
day1 420 50
day2 380 40
day3 390 45
Exmaple:
import pandas as pd
# list of strings
lst = [['Python ', 'is', 'easy', 'programming', 'language'],
['You ', 'can', 'learn', 'python', 'here']]
# Calling DataFrame constructor on list
df = [Link](lst)
print(df)
OUTPUT:
0 1 2 3 4
0 Python is easy programming language
1 You can learn python here
Read CSV Files
A simple way to store big data sets is to use CSV files (comma
separated files).
CSV files contains plain text and is a well know format that can be
read by everyone including Pandas.
import pandas as pd
df = pd.read_csv('[Link]')
print(df)
print(df.to_string()) #use to_string() to print the entire DataFrame.
Some Important Function and Attributes of Pandas
Function / Attribute Syntax / Usage Detailed Description
Reads data from a CSV (Comma Separated Values)
read_csv() pd.read_csv("[Link]") file and converts it into a Pandas DataFrame for
analysis and manipulation.
A two-dimensional, size-mutable, and labeled data
DataFrame df = [Link]() structure with rows and columns, similar to an
Excel spreadsheet or SQL table.
Displays the first five rows of the DataFrame by
head() [Link]() default; helps in understanding the structure and
contents of the dataset.
Displays the last five rows of the DataFrame; useful
tail() [Link]() for checking recently added or ending records.
Provides a concise summary of the DataFrame,
info() [Link]() including column names, data types, non-null
values, and memory usage.
Returns a tuple representing the dimensions of the
shape [Link] DataFrame in the form (number of rows, number of
columns).
Returns a list of all column names present in the
columns [Link] DataFrame.
Used to select a single column from the
Column Selection df["Marks"] DataFrame; returns a Series object.
Selects more than one column at a time; returns a
Multiple Columns df[["Name","Marks"]] new DataFrame.
Accesses rows or columns based on label-based
loc [Link][3] indexing. It is used when index labels are known.
Accesses rows or columns based on integer-
iloc [Link][5] position indexing, starting from 0.
Adds a new column to the DataFrame; values can
Adding Column df["Result"] = value be constants, lists, or computed using conditions.
Removes specified rows or columns from the
drop() [Link]("Result", axis=1) DataFrame. axis=1 refers to columns, axis=0 refers
to rows.
Calculates and returns the arithmetic mean
mean() df["Marks"].mean() (average) of the numerical column.
Returns the maximum (highest) value present in
max() df["Marks"].max() the specified numerical column.
Returns the minimum (lowest) value present in
min() df["Marks"].min() the specified numerical column.
Sorts the DataFrame data based on the values of a
sort_values() df.sort_values(by="Marks") given column in ascending or descending order.
Checks and returns True for missing (NaN) values
isnull() [Link]() and False for valid values in the DataFrame.
Replaces missing (NaN) values in the DataFrame
fillna() [Link](0) with a specified value such as 0, mean, or any
constant.
Removes rows or columns that contain missing
dropna() [Link]() (NaN) values from the DataFrame.
Writes the DataFrame data into a CSV file for
to_csv() df.to_csv("[Link]") storage or further use.
**For below example program we will use the “students_data.csv” file, which have 4 columns
(student_ID, Name, Age, Marks) and 12 rows.
import pandas as pd
# 1. Read CSV file
df = pd.read_csv("students_12_records.csv")
print(df)
# 2. Display first 5 records
print([Link]())
# 3. Display last 5 records
print([Link]())
# 4. Dataset information
[Link]()
# 5. Shape of DataFrame
print([Link])
# 6. Column names
print([Link])
# 7. Select single column
print(df["Marks"])
# 8. Select multiple columns
print(df[["Name", "Age"]])
# 9. loc (label-based indexing)
print([Link][3])
# 10. iloc (position-based indexing)
print([Link][5])
# 11. Add a new column
df["Result"] = "Pass"
print("\n--- After Adding Result Column ---")
print(df)
# 12. Statistical operations
print("\n--- Statistics on Marks ---")
print("Mean:", df["Marks"].mean())
print("Max:", df["Marks"].max())
print("Min:", df["Marks"].min())
# 13. Sorting values
print(df.sort_values(by="Marks", ascending=False))
# 14. Check for missing values
print([Link]())
# 15. Fill missing values (demo)
[Link](0, inplace=True)
# 16. Drop rows with missing values (demo)
[Link](inplace=True)
# 17. Drop a column
[Link]("Result", axis=1, inplace=True)
print("\n--- After Dropping Result Column ---")
print(df)
# 18. Save updated DataFrame to CSV
df.to_csv("students_updated.csv", index=False)
print("\nData successfully saved to students_updated.csv")
Fetching Selected Records from a CSV File (Filtering Records)
Filtering means selecting only those rows from a DataFrame that satisfy a specific condition.
(Like Students with Marks ≥ 90)
To fetch selected records from a CSV file in Python, we load the file using pd.read_csv(),
define a condition (e.g. df["Marks"] >= 90), and apply it on the DataFrame. The result
df[condition] returns only those rows where the condition is True. Multiple conditions can be
combined using &, |, and ~.
How Filtering Works:
Filtering uses Boolean conditions:
Every comparison returns True or False for each row.
Rows with True are selected.
import pandas as pd
df = pd.read_csv("students_data.csv")
# Define condition(s) — for example: Marks >= 90
condition = df["Marks"] >= 90
filtered_df = df[condition]
print(filtered_df)
OR you can write it in short as:
import pandas as pd
df = pd.read_csv("students_data.csv")
print( df [df ["Marks"] >= 90 ] )
Example to apply multiple conditions:
import pandas as pd
df = pd.read_csv("students_data.csv")
print( df [ (df ["Age"] > 21) & ( df ["Marks"] > 85) ])
GUI Programming
Graphical User Interface(GUI) is a form of user interface which
allows users to interact with computers through visual indicators
using items such as icons, menus, windows, etc.
It has advantages over the Command Line Interface(CLI) where
users interact with computers by writing commands using keyboard
only and whose usage is more difficult than GUI.
Python has a lot of GUI frameworks, but Tkinter is the only
framework that’s built into the Python standard library.
What is Tkinter?
Tkinter is the inbuilt python module that is used to create GUI
applications. It is one of the most commonly used modules for
creating GUI applications in Python as it is simple and easy to work
with.
An empty Tkinter top-level window can be created by using the
following steps.
1) import the Tkinter module.
2) Create the main application window.
3) Add the widgets like labels,buttons,frames,etc. to the window.
4) Call the main event loop so that the actions can take place on
the user's computer screen.
Fundamental structure of tkinter program
Importing tkinter is same as importing any other module in the
python code.
from tkinter import *
After importing tkinter module we need to create a main window,
tkinter offers a method ‘Tk()’ to create main window. The basic code
used to create the main window of the application is:
top = [Link]()
(or)
top = Tk()
After creating main window, we need to add components or widgets
like labels, buttons, frames, etc.
After adding widgets to main window, we need to run the
application, tkinter offers a method ‘mainloop()’ to run
application. The basic code used to run the application is:
[Link]()
EXAMPLE:
from tkinter import *
#creating the application main window.
top = Tk()
#Entering the event main loop
[Link]()
Tkinter widgets:
Widgets in Tkinter are the elements of GUI application which
provides various controls (such as Labels, Buttons, ComboBoxes,
CheckBoxes, MenuBars, RadioButtons and many more) to users to
interact with the application.
Basic Tkinter Widgets:
Button(root, text="Click", command=func)
This line creates a Button widget in Tkinter.
Button → Tkinter class used to create a button.
root → The parent window or frame where the button will appear.
text="Click" → This sets the label on the button, Whatever is written here will appear on the button.
command=func → This tells Tkinter which function to run when the button is clicked. func must be
the name of a function without parentheses.
Some Important Tkinter Widgets
Widget Description Basic Syntax
Label Displays text or images on the window. Label(root, text="Hello")
Creates a clickable button to perform an
Button Button(root, text="Click", command=func)
action.
Canvas Used for drawing shapes, images, graphics. Canvas(root, width=200, height=200)
ComboBox Drop-down list to select one option. [Link](root, values=["A","B","C"])
Provides toggle options; multiple selections
CheckButton Checkbutton(root, text="Option", variable=v)
allowed.
Allows only one option selection from a Radiobutton(root, text="Male", variable=v,
RadioButton
group. value=1)
Entry Single-line text input field. Entry(root)
Frame Container to group and organize widgets. Frame(root)
Similar to Label but displays multi-line
Message Message(root, text="Long message")
wrapped text.
Slider to select a numeric value from a
Scale Scale(root, from_=0, to=100)
range.
Scrollbar Scrolls contents in Text/Listbox/Canvas. Scrollbar(root, orient="vertical")
SpinBox Select a value using up/down arrows. Spinbox(root, from_=1, to=10)
Text Multi-line text input box; editable. Text(root, height=5, width=30)
Menu Creates menus (File, Edit, etc.). Menu(root)
Python Tkinter Geometry:
The Tkinter geometry specifies the method by using which, the
widgets are represented on display. The python Tkinter provides the
following geometry methods.
1. The pack() method – It is used to organize widget in the block. The
positions widgets added to the python application can be controlled
by using the various options specified in the method call.
2. The grid() method – It organizes the widgets in the tabular form.
We can specify the rows and columns as the options in the method
call.
3. The place() method - It organizes the widgets to the specific x and
y coordinates.
Ex:
from tkinter import *
def func():
print("Hello!")
root = Tk()
btn = Button(root, text="Click", command=func)
[Link]()
[Link]()
EXAMPLE: (pack() method)
from tkinter import *
parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
[Link]( side = LEFT)
blackbutton = Button(parent, text = "Black", fg = "black")
[Link]( side = RIGHT )
bluebutton = Button(parent, text = "Blue", fg = "blue")
[Link]( side = TOP )
greenbutton = Button(parent, text = "Green", fg = "green")
[Link]( side = BOTTOM)
[Link]()
EXAMPLE: (grid() method)
from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 2, column = 0)
[Link]()
EXAMPLE: (place() method)
from tkinter import *
top = Tk()
[Link]("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
[Link]()
from tkinter import *
def add():
n1 = int([Link]())
n2 = int([Link]())
[Link](n1 + n2)
def subtract():
n1 = int([Link]())
n2 = int([Link]())
[Link](n1 - n2)
root = Tk()
[Link]("300x250")
# Variables
num1 = StringVar()
num2 = StringVar()
result = StringVar()
# Widgets
Label(root, text="Enter Number 1").pack()
Entry(root, textvariable=num1).pack()
Label(root, text="Enter Number 2").pack()
Entry(root, textvariable=num2).pack()
Button(root, text="Add", command=add).pack()
Button(root, text="Subtract", command=subtract).pack()
Label(root, text="Result").pack()
Entry(root, textvariable=result, state="readonly").pack()
[Link]()
=============================================================================
Explanation:
num1 = StringVar() : Creates a Tkinter variable that will store Number 1 entered by the user. It connects the
Entry widget to this variable. When the user types a number, it is stored inside num1.
result = StringVar() : Used to store the final answer (result of addition or subtraction).
command=add : It is used to bind a function to the button click event.