1|P age
St. Francis Institute of Technology
An Autonomous Institute, Affiliated to University of Mumbai
NAAC A+ Accredited | CMPN, EXTC, INFT NBA Accredited | ISO9001:2015 Certified
PYP- MODULE 5- GUI
A Graphical User Interface (GUI) in Python is a visual interface that allows users
to interact with software using graphical elements like buttons, text fields, labels, and
other widgets, instead of typing commands into a terminal or using text-based
commands. The goal of a GUI is to make the interaction more intuitive and user-
friendly by presenting the user with familiar visual elements.
Significance of GUI in Python:
1. User-Friendliness: A GUI makes applications more accessible to users who
may not be familiar with programming or command-line interfaces.
2. Enhanced Experience: GUIs can provide a richer experience by incorporating
images, colors, and interactive components like buttons and sliders that can
visually represent the application's functionality.
3. Platform Independence: GUI applications created in Python can run across
different platforms like Windows, macOS, and Linux, making Python a
powerful tool for cross-platform development.
4. Increased Productivity: A GUI allows users to interact with the application
more efficiently, improving the overall productivity of using the software.
Tkinter: A Python Library for GUIs
Tkinter is the standard library in Python used to create GUIs. It provides a set of tools
to create windows, buttons, labels, menus, and other GUI components. Tkinter is a
wrapper around the Tk GUI toolkit, which is widely used in Python for developing
desktop applications.
—------------------------------------------------------------------------------------------------
Prepared by Harshal P G
2|P age
To create a root window along with its title and size using tkinter.
import tkinter as tk
# Create main window
root = tk.Tk()
root.title("My Tkinter Window") # Set window title
root.geometry("400x300") # Set window size
# Run the application
root.mainloop()
—-------------------------------------------------------------------------------------------------
Various widgets available in tkinter
1. Label:
Purpose: Displays text or an image on the screen. Labels are used for
providing instructions or displaying information. Example:
label = tk.Label(root, text="Hello, World!")
2. Button:
○ Purpose: A clickable button that can trigger a function or an action
when clicked. Example:
button = tk.Button(root, text="Click Me", command=some_function)
3. Entry:
○ Purpose: A single-line text input field where the user can type in data.
Example: entry = tk.Entry(root)
4. Text:
○ Purpose: A multi-line text input field for entering larger amounts of
text, often used for comments, descriptions, or long text inputs.Example:
text = tk.Text(root)
5. Checkbutton:
○ Purpose: A checkbox widget used to let the user select one or more
options. Example:
checkbutton = tk.Checkbutton(root, text="Accept Terms", variable=var)
Prepared by Harshal P G
3|P age
6. Radiobutton:
○ Purpose: A set of options where only one option can be selected at a
time, typically used for multiple-choice questions.Example:
radiobutton = tk.Radiobutton(root, text="Option 1", variable=var,
value=1)
7. Listbox:
○ Purpose: Displays a list of items, allowing the user to select one or
more items from the list. Or even the items can be added by user.
Example:
listbox = tk.Listbox(root)
listbox.insert(tk.END, "Item 1")
listbox.insert(tk.END, "Item 2")
listbox.pack()
8. Spinbox:
○ Purpose: A widget that allows the user to select a value from a
predefined range of values using arrows to increase or decrease the
value.Example:
spinbox = tk.Spinbox(root, from_=1, to=10)
9. Scale:
○ Purpose: A slider widget that allows the user to select a value from a
range by sliding a knob along a scale.Example:
scale = tk.Scale(root, from_=0, to=100, orient="horizontal")
10. Canvas:
○ Purpose: A versatile widget used for drawing shapes, images, and
custom graphics. It is useful for tasks like drawing lines, rectangles, or
even displaying custom images.Example:
canvas = tk.Canvas(root, width=200, height=200)
Prepared by Harshal P G
4|P age
11. Message :
○ Purpose: Similar to a Label but designed for displaying multiple lines
of text or messages. It is often used when you need to display more
extensive information, such as instructions or descriptive text, that may
require word wrapping. Example:
message = tk.Message(root, text="This is a longer message that can
span multiple lines.", width=200)
message.pack()
—--------------------------------------------------------------------------------------------------
To create different shapes in canvas using tkinter.
import tkinter as tk
# Create main window
root = tk.Tk()
root.title("Canvas Shapes")
root.geometry("400x400")
# Create a Canvas widget
canvas = tk.Canvas(root, width=350, height=350,
bg="white")
canvas.pack(pady=20)
# Draw shapes
canvas.create_rectangle(50, 50, 150, 150, fill="red") # Rectangle
canvas.create_oval(170, 50, 270, 150, fill="blue") # Oval
canvas.create_line(50, 200, 270, 200, width=3, fill="black") # Line
canvas.create_polygon(150, 250, 200, 300, 100, 300, fill="green") # Triangle
canvas.create_text(250, 250, text="Hello", font=("Arial", 16), fill="brown") # Text
# Run the application
root.mainloop()
—----------------------------------------------------------------------------------------------
Prepared by Harshal P G
5|P age
To display a frame using tkinter
import tkinter as tk
# Create main window
root = tk.Tk()
root.title("Frame Example")
root.geometry("400x400")
# Create a Frame widget
frame = tk.Frame(root, width=200, height=200,
bg="yellow")
frame.pack(pady=50)
# Run the application
root.mainloop()
—-----------------------------------------------------------------------------------------------
To develop GUI code to get the output window as shown below-
import tkinter as tk
root = tk.Tk()
root.title("Tkinter Widgets Example")
# Label
label = tk.Label(root, text="Enter your name:")
label.pack()
# Entry
entry = tk.Entry(root, width=20)
entry.pack()
Prepared by Harshal P G
6|P age
# Checkbutton
check_var = tk.BooleanVar()
checkbutton = tk.Checkbutton(root, text="Subscribe to newsletter",
variable=check_var)
checkbutton.pack()
# Radiobuttons
radio_var = tk.IntVar()
radiobutton1 = tk.Radiobutton(root, text="Option 1", variable=radio_var, value=1)
radiobutton1.pack()
radiobutton2 = tk.Radiobutton(root, text="Option 2", variable=radio_var, value=2)
radiobutton2.pack()
# Button
def on_button_click():
print(f"Name: {entry.get()}, Subscribed: {check_var.get()}, Selected Option:
{radio_var.get()}")
button = tk.Button(root, text="Submit", command=on_button_click)
button.pack()
# Run the application
root.mainloop()
—----------------------------------------------------------------------------------------------
pandas theory :
Pandas is a powerful Python library used for data manipulation and analysis. It
provides easy-to-use data structures and data analysis tools that make it efficient for
handling large datasets. It simplifies many tasks such as data cleaning,
transformation, exploration, and visualization.
Key Features of Pandas:
1. Data Structures:
○ DataFrame: A 2D table-like structure (rows and columns) used to store
and manipulate data, similar to a spreadsheet.
Prepared by Harshal P G
7|P age
○ Series: A Pandas Series is like a column in a tab. It is a one-dimensional
array holding data of any typele
2. Handling Missing Data:
○ Pandas offers functions like fillna() to replace missing values and
dropna() to remove missing values, making data clean-up easy.
3. Data Selection and Filtering:
○ It allows easy data selection using labels or conditions, enabling efficient
data filtering and manipulation.
4. Data Grouping and Aggregation:
○ GroupBy: This function helps in grouping data based on certain
conditions and performing operations like sum, mean, or count on each
group.
5. Merging and Joining:
○ You can combine multiple datasets using merge() and concat(), just
like SQL joins, making data integration straightforward.
6. Time Series Support:
○ Pandas has built-in tools for working with time-based data, allowing you
to perform operations like resampling and time-based indexing.
7. Data Transformation:
○ It provides functions for transforming data such as scaling, encoding, and
normalization.
Advantages of Pandas:
1. Easy to Use:
○ Pandas has a simple syntax that makes it easy for beginners and experts
to handle data efficiently.
2. Fast and Efficient:
○ Built on top of NumPy, it is optimized for fast performance, even with
large datasets.
Prepared by Harshal P G
8|P age
3. Flexible and Powerful:
○ Pandas allows complex data manipulation and transformation tasks with
just a few lines of code.
4. Integration with Other Libraries:
○ It integrates well with libraries like Matplotlib (for plotting), NumPy
(for numerical operations), and Scikit-learn (for machine learning).
5. Comprehensive I/O Functions:
○ Pandas can read from and write to various file formats like CSV, Excel,
SQL databases, and JSON, which makes data import/export easy.
6. Data Exploration:
○ Functions like head(), tail(), and describe() help quickly
explore and summarize datasets, making it easy to get insights.
—--------------------------------------------------------------------------------------------------
Practice Example on pandas- Write the output. (Assignment 2) �
import pandas as pd
# Data for students
data = {
'Name': ['Kedar', 'Bhavesh', 'Charlie', 'David', 'Mohan'],
'Age': [20, 21, 22, 23, 20],
'Marks': [85, 78, 92, 88, 95]
}
# Creating DataFrame
df = pd.DataFrame(data)
print(df.head())
—--------------------------------------------------------------------------------------------------
Prepared by Harshal P G
9|P age
Practice Example on pandas :
import pandas as pd
# Create a DataFrame from a dictionary
data = {
"Student": ["Minal", "Namita", "Kedar", "Saurav", "vansh"],
"Score": [85, 92, 78, 88, 95]
}
df = pd.DataFrame(data)
# Display the first 3 rows
print("First 3 Rows of DataFrame:\n", df.head(3))
# Calculate the average score
average_score = df["Score"].mean()
print("\nAverage Score of Students:", average_score)
—--------------------------------------------------------------------------------------------------
Practice Example on numpy
import numpy as np
# Array of student marks
marks = np.array([85, 78, 92, 88, 95, 77, 84, 91])
# Calculate average, highest, and lowest marks
average_marks = np.mean(marks)
highest_marks = np.max(marks)
lowest_marks = np.min(marks)
# Display the results
print(f"Average Marks: {average_marks}")
print(f"Highest Marks: {highest_marks}")
print(f"Lowest Marks: {lowest_marks}")
Output:
Average Marks: 85.0
Highest Marks: 95
Lowest Marks: 77
Prepared by Harshal P G
10 | P a g e
Practice program on numpy – Write output. (Assignment 2)
import numpy as np
# Step 1: Create a 3x3 matrix with values from 1 to 9
matrix = np.arange(1, 10).reshape(3, 3)
print("3x3 Matrix:\n", matrix)
# Step 2: Compute the sum of all elements in the matrix
sum_of_elements = np.sum(matrix)
print("\nSum of all elements in the matrix:", sum_of_elements)
—--------------------------------------------------------------------------------------------------
Practice Example on pandas & numpy : Write the output. (Assignment 2)
# Import NumPy and Pandas
import numpy as np
import pandas as pd
# Declare an array and perform mathematical operations
arr = np.array([1, 2, 3, 4, 5])
print("Original Array:", arr)
squared_arr = np.square(arr) # Square of each element
mean_value = np.mean(arr) # Mean of the array
print("Squared Array:", squared_arr)
print("Mean Value:", mean_value)
# Create a 2D array (Matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("\nOriginal Matrix:\n", matrix)
# Perform Transpose of the Matrix
transposed_matrix = np.transpose(matrix)
print("\nTransposed Matrix:\n", transposed_matrix)
# Create a DataFrame using Pandas
data = {
"Name": ["Abha", "Bin", "neil"],
"Age": [25, 30, 22],
"Salary": [50000, 60000, 45000]
Prepared by Harshal P G
11 | P a g e
}
df = pd.DataFrame(data)
print("\nOriginal DataFrame:\n", df)
# Add a new column to the DataFrame
df["Department"] = ["HR", "IT", "Finance"]
print("\nDataFrame After Adding New Column:\n", df)
# Filter a column of the DataFrame (e.g., selecting only "Salary" column)
salary_column = df["Salary"]
print("\nFiltered Column (Salary):\n", salary_column)
# Save the DataFrame to a CSV file
df.to_csv("employee_data.csv", index=False)
print("\nDataFrame saved as 'employee_data.csv' successfully!")
output:
—-------------------------------------------------------------------------------------------------
Prepared by Harshal P G
12 | P a g e
Matplotlib Theory:
Matplotlib is a popular and powerful data visualization library in Python. It is widely
used for creating static, interactive, and animated visualizations in Python. With
Matplotlib, you can generate various types of plots, including line charts, bar charts,
histograms, and more, to help analyze and understand data visually.
Significance of Matplotlib:
● Data Visualization: It helps in transforming data into graphical
representations, making it easier to understand and interpret.
● Customization: It offers a high degree of customization, allowing users to
adjust almost every element of a plot, such as labels, titles, colors, and more.
● Interactivity: Matplotlib supports interactive plotting, which is useful for
exploring data dynamically.
● Integration: It integrates well with other libraries like NumPy, Pandas, and
Seaborn, which makes it ideal for data analysis and scientific computing.
● Wide Use: Matplotlib is the foundation for many other Python visualization
libraries, such as Seaborn and ggplot.
Key Features of Matplotlib:
1. Wide Range of Plots: It supports a variety of plot types such as line plots, bar
plots, scatter plots, pie charts, histograms, etc.
2. Customizable: You can customize almost every part of a plot, including colors,
labels, legends, ticks, and axes.
3. Publication Quality: Matplotlib generates high-quality graphics suitable for
publications or presentations.
4. Multiple Backends: It supports different backends for rendering graphics,
allowing you to save plots in various formats like PNG, PDF, SVG, and more.
5. Interactive Plots: It has interactive plotting features that allow zooming,
panning, and updating plots dynamically (e.g., using Matplotlib’s widget
module).
Prepared by Harshal P G
13 | P a g e
6. 3D Plotting: With mpl_toolkits.mplot3d, Matplotlib supports 3D plotting for
visualizing complex data in three dimensions.
7. Integration with Other Libraries: It works seamlessly with libraries like
Pandas and NumPy to handle and visualize data efficiently.
Different Types of Plots Supported by Matplotlib:
—-------------------------------------------------------------------------------------------------
Prepared by Harshal P G
14 | P a g e
Practice Example on matplotlib
import matplotlib.pyplot as plt
# Sales data for the months Jan to June
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [5000, 6000, 7500, 8000, 9000, 9500]
# Creating the bar chart
plt.bar(months, sales, color='skyblue')
# Adding labels and title
plt.xlabel('Months')
plt.ylabel('Sales (in USD)')
plt.title('Sales Data for the First Half of the Year')
# Display the chart
plt.show()
—--------------------------------------------------------------------------------------------------
** codes for other types of plot
# Line chart
axs[0, 1].plot(months, sales, marker='o', color='teal')
axs[0, 1].set_title('Line Chart')
axs[0, 1].set_xlabel('Months')
axs[0, 1].set_ylabel('Sales')
----------------------------------------------------------------------------------------------------
# Scatter plot
axs[1, 0].scatter(months, sales, color='darkorange')
axs[1, 0].set_title('Scatter Plot')
axs[1, 0].set_xlabel('Months')
axs[1, 0].set_ylabel('Sales')
---------------------------------------------------------------------------------------------------
Prepared by Harshal P G
15 | P a g e
Prepared by Harshal P G