NumPy Basics: Fast Array Operations
NumPy Basics: Fast Array Operations
Q. What is NumPy?
NumPy (Numerical Python) is a Python library used for fast mathematical and numerical
operations.
It is mainly used to work with arrays, do matrix operations, and perform scientific
calculations efficiently.
1. Faster than Python lists – Because NumPy is written in C, operations are very fast.
3. Has powerful mathematical functions – Like sum, mean, standard deviation, dot
product.
4. Foundation for ML and DL – Libraries like Pandas, TensorFlow, PyTorch internally use
NumPy.
Key Features:
1. ndarray: Multi-dimensional array (1D, 2D, 3D…).
NumPy is faster because it uses optimized C code, stores data in continuous memory,
and performs vectorized operations without Python loops.
Installation of NumPy
[Link] 1/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
print([Link](li))
[1 2 3 4]
[5 6 7 8]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
2. Initial Placeholders
[1 2 3 4 5 6 7 8 9]
[ 1. 5.5 10. ]
[0 0 0 0 0]
[1 1 1 1 1]
[4 2 1 4 0 4 2 1 4 1]
[Link] 2/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
[[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]]
[[1 1 1]
[1 1 1]
[1 1 1]
[1 1 1]]
[[67 67]
[67 67]]
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
3. Inspecting Properties
In [ ]: NumPy arrays possess some basic properties that can be used to get information
about the array such as the size, length, shape, and datatype of the array.
Numpy arrays can also be converted to a list and be change their datatype.
Size: 4
len: 4
Shape: (4,)
Datatype: int32
[Link] 3/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
print(arr)
print("Datatype:", [Link])
[1. 2. 3. 4.]
Datatype: float64
arr
Size: 12
[Link] 4/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
Length: 3
Shape: (3, 4)
Datatype: int32
[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
float64
List: [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]]
<class 'list'>
3. Sorting Array
[Link] 5/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
Original Array
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
[Link] 6/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
1D arr: [1 2 3 4]
Original arr: [1 2 3 4]
Reshaping Array
# printing array
print("Array: " + str(array))
Array: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
print(reshaped1)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
[Link] 7/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
2-D Array:
[1 2 3 4]
Resizing an Array
[[1 2 3 4]
[5 6 0 0]
[0 0 0 0]]
print([Link]())
[1 2 3 4 5 6 7 8]
Transpose
# before transpose
print(ncs, end ='\n\n')
# after transpose
print([Link](1, 0))
[Link] 8/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
[[1 2]
[4 5]
[7 8]]
[[1 4 7]
[2 5 8]]
[Link]()
[[1 2]
[3 4]
[5 6]
[7 8]]
[Link]()
[Link] 9/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
vs = [Link](arr2, 3)
In [72]: arr2
In [82]: hs = [Link](arr2, 1)
hs
Subsetting
print(subset)
[12 20 18]
print(subset)
[12 18]
Slicing Array
print(arr[1:4])
print(arr[:3])
print(arr[2:])
print(arr[0:5:2])
print(arr[::-1])
[Link] 10/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
[20 30 40]
[10 20 30]
[30 40 50]
[10 30 50]
[50 40 30 20 10]
print(arr2[0:2, 1:3])
print(arr2[1, :])
print(arr2[:, 2])
[[2 3]
[5 6]]
[4 5 6]
[3 6 9]
Indexing
10
30
40
print(arr2[0, 1])
print(arr2[1, 2])
print(arr2[0])
print(arr2[:, 1])
10
30
[ 5 10 15]
[10 25]
A view means the new array points to the same data as the original array.
view_arr[1] = 99
[Link] 11/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
[10 99 30 40]
[10 99 30 40]
A copy means NumPy creates a new array with new memory storage.
copy_arr[1] = 99
[10 20 30 40]
[10 99 30 40]
Out[94]: False
Arithmetic Operations
[Link] 12/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
# Performing Exponentiation
print("Exponentiation:", [Link](b))
Addition: [ 7 77 23 130]
************************************************************
Subtraction: [ 3 67 3 70]
************************************************************
Multiplication: [ 10 360 130 3000]
************************************************************
Division: [ 2.5 14.4 1.3 3.33333333]
************************************************************
Mod: [ 1 2 3 10]
************************************************************
Remainder: [ 1 2 3 10]
************************************************************
Power: [ 25 1934917632 419538377 0]
************************************************************
Exponentiation: [7.38905610e+00 1.48413159e+02 2.20264658e+04 1.06864746e+13]
Comparison
print(equal_arrays)
True
Vector Math
[Link] 13/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
Statistic
In [100… # 1D array
arr = [20, 2, 7, 1, 34]
# mean
print("mean of arr:", [Link](arr))
print("*" * 60)
# median
print("median of arr:", [Link](arr))
print("*" * 60)
# sum
print("Sum of arr(uint8):", [Link](arr, dtype = np.uint8))
print("Sum of arr(float32):", [Link](arr, dtype = np.float32))
print("*" * 60)
# var
print("var of arr:", [Link](arr))
print("*" * 60)
# standard deviation
print("std of arr:", [Link](arr))
[Link] 14/15
11/19/25, 12:49 PM NumPy_Cheat_Sheet
corrcoef
print(rslt)
[[1. 1.]
[1. 1.]]
In [ ]:
[Link] 15/15
11/24/25, 12:45 PM Pandas_cheat_sheet
What is Pandas?
2.1.4
Out[3]: A Geeks
B for
C geeks
dtype: object
Out[6]: (4, 3)
<class '[Link]'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Fruits 4 non-null object
1 Quantity 4 non-null int64
2 Price 4 non-null int64
dtypes: int64(2), object(1)
memory usage: 228.0+ bytes
[Link]()
<class '[Link]'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Fruits 4 non-null object
1 Quantity 4 non-null int32
2 Price 4 non-null float64
dtypes: float64(1), int32(1), object(1)
memory usage: 212.0+ bytes
In [9]: [Link]
Reshaping
variable value
0 FRUITS Mango
1 FRUITS Apple
2 FRUITS Banana
3 FRUITS Orange
4 QUANTITY 40
5 QUANTITY 20
6 QUANTITY 25
7 QUANTITY 10
8 PRICE 80.0
9 PRICE 100.0
10 PRICE 50.0
11 PRICE 70.0
FRUITS PRICE
0 Mango 80.0
1 Apple 100.0
2 Banana 50.0
3 Orange 70.0
0 Mango
1 Apple
2 Banana
3 Orange
Name: FRUITS, dtype: object
FRUITS PRICE
0 Mango 80.0
1 Apple 100.0
2 Banana 50.0
3 Orange 70.0
FRUITS QUANTITY
0 Mango 40
1 Apple 20
2 Banana 25
3 Orange 10
['FRUITS', 'PRICE']])
FRUITS PRICE
2 Banana 50.0
FRUITS PRICE
0 Mango 80.0
1 Apple 100.0
2 Banana 50.0
3 Orange 70.0
Out[31]: 100.0
Filter
FRUITS PRICE
0 Mango 80.0
1 Apple 100.0
2 Banana 50.0
3 Orange 70.0
Where
Out[34]: 0 80.0
1 100.0
2 NaN
3 70.0
Name: PRICE, dtype: float64
Query
Pandas query() methods return the filtered data frame.
In [37]: # QUERY
print([Link]('PRICE>70'))
Fruits Price
0 Mango 60
1 Banana 40
2 Grapes 75
3 Apple 100
4 Orange 65
Fruits Price
0 Apple 120
1 Orange 60
2 Papaya 30
3 Pineapple 70
4 Mango 50
A. Left Join
B. Right Join
C. Inner Join
D. Outer Join
Concatenation
Describe dataset
In [48]: print([Link]())
In [49]: print([Link](include=['O']))
FRUITS
count 6
unique 6
top Mango
freq 1
Unique values
Out[51]: FRUITS
Mango 1
Apple 1
Banana 1
Orange 1
Grapes 1
Pineapple 1
Name: count, dtype: int64
print(df['PRICE'].sum())
390.0
print(df['PRICE'].cumsum())
0 80.0
1 180.0
2 230.0
3 300.0
4 360.0
5 390.0
Name: PRICE, dtype: float64
Out[54]: 30.0
Out[55]: 100.0
Out[56]: 65.0
Out[57]: 65.0
In [58]: # Variance
df['PRICE'].var()
Out[58]: 590.0
Out[59]: 24.289915602982237
In [60]: # Quantile
df['PRICE'].quantile([0, 0.25, 0.75, 1])
Covariance
In [61]: print([Link](numeric_only=True))
Correlation
In [62]: print([Link](numeric_only=True))
Missing Values
Check for null values using isnull() function.
FRUITS 0
QUANTITY 0
PRICE 0
DISCOUNT 1
dtype: int64
Mean = [Link]()
Group By
Group the DataFrame by the 'Origin' column using groupby() methods
grouped = [Link]('Origin')
print(grouped[numeric_cols].agg(['sum', 'mean']))
Histogram
[Link]() methods is used to create a histogram.
In [85]: df['QUANTITY'].[Link](bins=3)
[Link]()
Pie Chart
[Link]() methods used to create pie chart.
In [102… [Link]('Origin')['TOTAL'].sum().[Link](
autopct='%1.1f%%', # show percentages
startangle=90, # rotate pie for better view
figsize=(6,6), # size of plot
shadow=True, # add slight shadow
legend=True # show legend
)
In [ ]:
📌 Matplotlib
#️⃣ 1. What is Matplotlib?
Matplotlib is a Python plotting library used to create static, animated, and interactive
visualizations. It works well with NumPy and Pandas, and is widely used in Data
Analysis and Machine Learning.
Types of Data
1. Numerical Data
Data represented in numbers (e.g., age, salary, marks).
Used for mathematical calculations.
2. Categorical Data
Data divided into categories or labels (e.g., gender, city, department).
Used for grouping and classification.
2D line plots
[Link] 1/41
11/24/25, 5:43 PM session_1_matplotlib
bivariate Analysis
categorical->numerical and numerical ->numerical
use case- Time series Data
📌 2D Line Plots
✔️ What is a 2D Line Plot?
A 2D line plot shows the relationship between two numerical variables using a
continuous line.
✔️ Basic Syntax
[Link](x, y)
[Link]()
| Parameter | Description |
| ------------------- | ------------------------------------------- |
| `x`, `y` | Data points |
| `color` / `c` | Line color |
| `linestyle` / `ls` | Type of line (`'-'`, `'--'`, `':'`, `'-.'`) |
| `linewidth` / `lw` | Line thickness |
| `marker` | Marker style (`'o'`, `s`, `*`, `^'`) |
| `markersize` / `ms` | Size of markers |
| `label` | For legend |
| `alpha` | Transparency level (0 to 1) |
[Link] 2/41
11/24/25, 5:43 PM session_1_matplotlib
[Link](year,price)
[Link] 3/41
11/24/25, 5:43 PM session_1_matplotlib
[Link] 4/41
11/24/25, 5:43 PM session_1_matplotlib
[Link](batsman['index'],batsman['RG Sharma'])
[Link]('Rohit sharma VS virat kohli career comparison')
[Link] 5/41
11/24/25, 5:43 PM session_1_matplotlib
In [12]: # colors (hex) and line (width and style) and marker size
[Link](batsman['index'],batsman['V Kohli'],color='green')
[Link](batsman['index'],batsman['RG Sharma'],color='red')
[Link]('Rohit sharma VS virat kohli career comparison')
[Link]('Season')
[Link]('runs scored')
[Link] 6/41
11/24/25, 5:43 PM session_1_matplotlib
[Link] 7/41
11/24/25, 5:43 PM session_1_matplotlib
[Link] 8/41
11/24/25, 5:43 PM session_1_matplotlib
[Link] 9/41
11/24/25, 5:43 PM session_1_matplotlib
In [22]: # legend->location->label
[Link](batsman['index'],batsman['V Kohli'],color='green',linestyle='solid',lin
[Link](batsman['index'],batsman['RG Sharma'],color='red',linestyle='dotted',li
[Link]('Rohit sharma VS virat kohli career comparison')
[Link]('Season')
[Link]('runs scored')
[Link]() # apne hissab se adjust kr skte hain jgah ko
[Link] 10/41
11/24/25, 5:43 PM session_1_matplotlib
[Link](year,price)
[Link] 11/41
11/24/25, 5:43 PM session_1_matplotlib
In [29]: price=[48000,54000,57000,49000,47000,45000,450000]
year=[2015,2016,2017,2018,2019,2020,2021]
[Link](year,price)
[Link](0,75000)
[Link](2017,2019)
[Link] 12/41
11/24/25, 5:43 PM session_1_matplotlib
In [30]: # grid
[Link](batsman['index'],batsman['V Kohli'],color='green',linestyle='solid',lin
[Link](batsman['index'],batsman['RG Sharma'],color='red',linestyle='dotted',li
[Link]('Rohit sharma VS virat kohli career comparison')
[Link]('Season')
[Link]('runs scored')
[Link]()
[Link]()
In [31]: # show
[Link](batsman['index'],batsman['V Kohli'],color='green',linestyle='solid',lin
[Link](batsman['index'],batsman['RG Sharma'],color='red',linestyle='dotted',li
[Link]('Rohit sharma VS virat kohli career comparison')
[Link]('Season')
[Link]('runs scored')
[Link]()
[Link]()
[Link] 13/41
11/24/25, 5:43 PM session_1_matplotlib
Scatter Plots
Bivariate analysis
numerical vs numerical
use case- finding correlation
📌 Scatter Plot —
✅ What is a Scatter Plot?
[Link] 14/41
11/24/25, 5:43 PM session_1_matplotlib
A scatter plot displays individual data points on a 2D plane to show the relationship
between two numerical variables.
Used to identify correlation, patterns, clusters, and outliers.
🟦 Basic Syntax
[Link](x, y)
[Link]()
| Parameter | Description |
| ------------- | ----------------------------------------- |
| `x`, `y` | Data points |
| `color` / `c` | Point color |
| `s` | Marker size |
| `marker` | Shape of point (`o`, `s`, `^`, `*`, etc.) |
| `alpha` | Transparency (0 to 1) |
| `label` | Name for legend |
| `edgecolor` | Border color of marker |
| `linewidths` | Border thickness |
In [33]: [Link](x,y)
[Link] 15/41
11/24/25, 5:43 PM session_1_matplotlib
[Link] 16/41
11/24/25, 5:43 PM session_1_matplotlib
[Link] 17/41
11/24/25, 5:43 PM session_1_matplotlib
In [36]: [Link](df['avg'],df['strike_rate'],color='red',marker='+')
[Link]('Avg and SR analysis of top 50 batsman')
[Link]('Average')
[Link]('SR')
[Link] 18/41
11/24/25, 5:43 PM session_1_matplotlib
In [38]: # size
tips=sns.load_dataset('tips')
#slower
[Link](tips['total_bill'],tips['tip'],s=tips['size']*15)
[Link] 19/41
11/24/25, 5:43 PM session_1_matplotlib
Bar chart
[Link] 20/41
11/24/25, 5:43 PM session_1_matplotlib
bivariate analysis
categorical vs numerical
use case- Aggregate analysis of groups
📌 Bar Chart —
✅ What is a Bar Chart?
A bar chart represents categorical data using rectangular bars whose height/length
shows the value.
Used for comparing categories, groups, frequencies, or totals.
[Link] 21/41
11/24/25, 5:43 PM session_1_matplotlib
🟦 Basic Syntax
[Link](categories, values)
[Link]()
| Parameter | Description |
| ----------- | ------------------- |
| `x` | Categories (labels) |
| `height` | Values |
| `color` | Bar color |
| `width` | Bar width |
| `label` | Label for legend |
| `edgecolor` | Border color |
| `linewidth` | Border thickness |
| `alpha` | Transparency |
[Link] 22/41
11/24/25, 5:43 PM session_1_matplotlib
[Link] 23/41
11/24/25, 5:43 PM session_1_matplotlib
In [52]: [Link]([Link]([Link][0]),df['2016'],width=0.2,color='blue')
[Link] 24/41
11/24/25, 5:43 PM session_1_matplotlib
In [52]: [Link]([Link]([Link][0]),df['2016'],width=0.2,color='blue')
[Link] 25/41
11/24/25, 5:43 PM session_1_matplotlib
In [55]: # xticks
[Link]([Link]([Link][0]) - 0.2,df['2015'],width=0.2,color='pink')
[Link]([Link]([Link][0]),df['2016'],width=0.2,color='blue')
[Link] 26/41
11/24/25, 5:43 PM session_1_matplotlib
[Link]([Link]([Link][0]) + 0.2,df['2017'],width=0.2,color='black')
[Link]([Link]([Link][0]),df['batsman'])
[Link]()
In [60]: # a problem
children=[10,20,40,10,30]
colors=['red red red red red red red','blue blue blue blue blue','green greengre
[Link](colors,children,color='pink')
[Link] 27/41
11/24/25, 5:43 PM session_1_matplotlib
In [59]: # solution
children=[10,20,40,10,30]
colors=['red red red red red red red','blue blue blue blue blue','green greengre
[Link](colors,children,color='pink')
[Link](rotation='vertical')
[Link]()
[Link] 28/41
11/24/25, 5:43 PM session_1_matplotlib
[Link] 29/41
11/24/25, 5:43 PM session_1_matplotlib
Histogram
univariate Analysis
Numerical col
use case- Frequency count
📌 Histogram —
✅ What is a Histogram?
[Link] 30/41
11/24/25, 5:43 PM session_1_matplotlib
It tells:
🟦 Basic Syntax
[Link](data)
[Link]()
| Parameter | Description |
| ------------- | ------------------------------------------------- |
| `x` | Data |
| `bins` | Number of bins or list of intervals |
| `color` | Bar color |
| `edgecolor` | Border color |
| `alpha` | Transparency |
| `label` | Legend label |
| `density` | Normalize to probability density |
| `orientation` | Vertical / Horizontal |
| `histtype` | `'bar'`, `'barstacked'`, `'step'`, `'stepfilled'` |
data=[32,45,56,10,15,27,61]
[Link](data)
Out[63]: (array([2., 0., 0., 1., 1., 0., 1., 0., 0., 2.]),
array([10. , 15.1, 20.2, 25.3, 30.4, 35.5, 40.6, 45.7, 50.8, 55.9, 61. ]),
<BarContainer object of 10 artists>)
[Link] 31/41
11/24/25, 5:43 PM session_1_matplotlib
In [69]: data=[32,45,56,10,15,27,61]
[Link](data,bins=[10,25,40,55,70])
[Link] 32/41
11/24/25, 5:43 PM session_1_matplotlib
0 12 62
1 17 28
2 20 64
3 27 0
4 30 10
136 624 75
138 632 54
139 633 0
140 636 54
In [71]: [Link](df['batsman_runs'],bins=[0,10,20,30,40,50,60,70,80,90,100,110,120])
Out[71]: (array([32., 29., 17., 21., 7., 14., 6., 7., 2., 2., 3., 1.]),
array([ 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.,
110., 120.]),
<BarContainer object of 12 artists>)
[Link] 33/41
11/24/25, 5:43 PM session_1_matplotlib
[Link] 34/41
11/24/25, 5:43 PM session_1_matplotlib
Pie Chart
univariate/Bivariate analysis
categorical vs numerical
use case - to find contribution on a standard scale
It helps show:
- Part-to-whole relationship
- Category-wise contribution
- Quick understanding of proportions
---
---
# 🟦 Basic Syntax
```python
[Link](data)
[Link]()
```
---
[Link] 35/41
11/24/25, 5:43 PM session_1_matplotlib
| Parameter | Description |
| ------------- | --------------------------------------------------- |
| `x` | Data values for slices |
| `labels` | Names of categories |
| `autopct` | Display percentage values on slices |
| `startangle` | Rotate the chart (0–360 degrees) |
| `explode` | Offset a slice to highlight |
| `colors` | List of colors |
| `shadow` | Add shadow effect |
| `radius` | Set pie chart size |
| `counterclock`| Draw slices clockwise or counterclockwise |
| `pctdistance` | Distance of % text from center |
---
# ✅ Summary
In [76]: data=[23,45,100,20,49]
subjects=['eng','sciecnee','math','sst','hindi']
[Link](data,labels=subjects)
[Link]()
[Link] 36/41
11/24/25, 5:43 PM session_1_matplotlib
In [77]: # dataset
df=pd.read_csv('[Link]')
df
0 AB de Villiers 31
1 CH Gayle 175
2 R Rampaul 0
3 SS Tiwary 2
4 TM Dilshan 33
5 V Kohli 11
In [78]: # percentage
[Link](df['batsman_runs'],labels=df['batsman'],autopct='%0.1f%%')
[Link]()
[Link] 37/41
11/24/25, 5:43 PM session_1_matplotlib
In [79]: # colors
[Link](df['batsman_runs'],labels=df['batsman'],autopct='%0.1f%%',colors=['blue'
[Link]()
[Link] 38/41
11/24/25, 5:43 PM session_1_matplotlib
In [82]: [Link](df['batsman_runs'],labels=df['batsman'],autopct='%0.1f%%',colors=['blue'
[Link]()
changing styles
In [83]: [Link]
[Link] 39/41
11/24/25, 5:43 PM session_1_matplotlib
Out[83]: ['Solarize_Light2',
'_classic_test_patch',
'_mpl-gallery',
'_mpl-gallery-nogrid',
'bmh',
'classic',
'dark_background',
'fast',
'fivethirtyeight',
'ggplot',
'grayscale',
'petroff10',
'seaborn-v0_8',
'seaborn-v0_8-bright',
'seaborn-v0_8-colorblind',
'seaborn-v0_8-dark',
'seaborn-v0_8-dark-palette',
'seaborn-v0_8-darkgrid',
'seaborn-v0_8-deep',
'seaborn-v0_8-muted',
'seaborn-v0_8-notebook',
'seaborn-v0_8-paper',
'seaborn-v0_8-pastel',
'seaborn-v0_8-poster',
'seaborn-v0_8-talk',
'seaborn-v0_8-ticks',
'seaborn-v0_8-white',
'seaborn-v0_8-whitegrid',
'tableau-colorblind10']
In [84]: [Link]('dark_background')
save figure
In [85]: [Link](df['batsman_runs'],labels=df['batsman'],autopct='%0.1f%%',colors=['blue'
[Link]('[Link]')
[Link] 40/41
11/24/25, 5:43 PM session_1_matplotlib
In [ ]:
[Link] 41/41
1. Introduction to Tkinter
Tkinter is Python’s standard library for creating Graphical User Interfaces (GUIs).
It provides tools to design windows, buttons, labels, textboxes, menus, and other GUI elements
easily.
To Import Tkinter:
from tkinter import *
Explanation:
2. Tkinter Widgets
A widget is a graphical element such as a button, label, or textbox.
Below are the most important widgets (with syntax + example + explanation).
root = Tk()
label = Label(root, text="Hello, Tkinter!", font=('Arial', 14), fg='blue')
[Link]()
[Link]()
Important Options:
root = Tk()
entry = Entry(root, width=30, bg='lightyellow', fg='black')
[Link]()
[Link]()
Options:
To get value:
data = [Link]()
def say_hello():
print("Hello!")
root = Tk()
btn = Button(root, text="Click Me", command=say_hello, bg='skyblue')
[Link]()
[Link]()
Options:
root = Tk()
frame = Frame(root, bg='lightgray', borderwidth=3, relief='sunken')
[Link](padx=10, pady=10)
[Link]()
root = Tk()
text = Text(root, height=5, width=40)
[Link]()
[Link]()
root = Tk()
var = IntVar()
check = Checkbutton(root, text="I agree", variable=var)
[Link]()
[Link]()
Get value:
root = Tk()
var = IntVar()
r1 = Radiobutton(root, text="Male", variable=var, value=1)
r2 = Radiobutton(root, text="Female", variable=var, value=2)
[Link]()
[Link]()
[Link]()
print([Link]())
root = Tk()
listbox = Listbox(root)
[Link](1, "Python")
[Link](2, "C++")
[Link](3, "Java")
[Link]()
[Link]()
root = Tk()
menu = Menu(root)
[Link](menu=menu)
[Link]()
(10) Messagebox
root = Tk()
def showmsg():
[Link]("Info", "Welcome to Tkinter!")
root = Tk()
scale = Scale(root, from_=0, to=100, orient=HORIZONTAL)
[Link]()
[Link]()
Get value:
val = [Link]()
root = Tk()
spin = Spinbox(root, from_=0, to=10)
[Link]()
[Link]()
3. Geometry Managers
Tkinter provides three geometry managers for layout:
Method Description
.pack() Automatic placement in block format
.grid() Arranges widgets in rows and columns
.place() Uses exact x, y coordinates
Example:
[Link](row=0, column=0)
[Link](row=0, column=1)
root = Tk()
[Link]("Student Form")
[Link]("400x300")
def submit():
[Link]("Info", f"Name: {[Link]()} | Age: {[Link]()} |
Gender: {[Link]()}")
Label(root, text="Name:").pack()
name = Entry(root)
[Link]()
Label(root, text="Age:").pack()
age = Entry(root)
[Link]()
Label(root, text="Gender:").pack()
gender = StringVar(value="Male")
Radiobutton(root, text="Male", variable=gender, value="Male").pack()
Radiobutton(root, text="Female", variable=gender, value="Female").pack()
[Link]()