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

DigitalSkills&Python_Chapter10

Chapter 10 of the document introduces the Tkinter module for creating Graphical User Interfaces (GUIs) in Python. It covers the basic steps for creating a Tkinter application, including setting up the main window, adding widgets, and handling events. Various widgets such as labels, buttons, entry fields, and menus are explained with examples to demonstrate their functionality.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

DigitalSkills&Python_Chapter10

Chapter 10 of the document introduces the Tkinter module for creating Graphical User Interfaces (GUIs) in Python. It covers the basic steps for creating a Tkinter application, including setting up the main window, adding widgets, and handling events. Various widgets such as labels, buttons, entry fields, and menus are explained with examples to demonstrate their functionality.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Digital Skills and Python Programming

Chapter 10
Python Graphical User Interface (GUI):
Introduction to Tkinter Module

Pr. Mehdia AJANA


Email: [email protected]
What is a Graphical User Interface (GUI):
PYTHON
• The Graphical User Interface (GUI) allows
GUI users to interact/communicate with the
computer and includes graphical
representations like buttons and icons.
• Communication can be performed by
interacting with these icons rather than the
Create First usual text-based or command-line
GUI Application communication.
Tkinter • Python offers multiple options and libraries
for developing GUI (Graphical User Interface),
e.g. Kivy, Python QT, wxPython, Tkinter…
• Python Tkinter is the simplest and most
commonly used method to create GUI
applications.

Pr. Mehdia AJANA 2


Tkinter Introduction:
PYTHON To create a Tkinter Python app, you follow these
GUI basic steps:
1. Import the tkinter module as tk: Tkinter
comes pre-installed with Python (built-in
module).
2. Create the main window (container) which
Create First serves as the container for all the GUI
elements you’ll add later.
GUI Application
3. Add widgets/elements to the main
Tkinter window: e.g. buttons, labels, entry fields,
etc., to the main window to design the
interface as desired.
4. Apply event triggers to the widgets: Enter
the main event loop to respond to user
interactions and attach event triggers to the
widgets.
Pr. Mehdia AJANA 3
Creating a Basic Tkinter Window:
PYTHON
• Tk() creates the main window.
GUI • title() sets the window title.
• mainloop() keeps the window open: It 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 open.
Create First import tkinter as tk
GUI Application window = tk.Tk()
Tkinter window.title("Simple Tkinter Window")
window.mainloop()

# You can set the


window's width
and height
window.geometry(
"500x300")
Pr. Mehdia AJANA 4
Tkinter Widgets:
PYTHON Widgets are elements you can add to your Tkinter
GUI window. There are a number of widgets which you
can put in your tkinter application.

Some of the major widgets include:

Create First
GUI Application
Tkinter

Pr. Mehdia AJANA 5


Tkinter Label Widget:
PYTHON The Label widget is used to display static text or
GUI images in the GUI:
Syntax: W = Label(master,options)
The master parameter denotes the parent window.
You can use many options to configure the text,
written as comma-separated key-value pairs.
Create First import tkinter as tk
GUI Application window = tk.Tk()
window.title("Simple Tkinter Window")
Tkinter window.geometry("500x300") #size widthxheight in
pixels
label = tk.Label(window, text="Hello, Tkinter!")
label.pack() # Positions the label in the window
window.mainloop()

6
Tkinter Label Widget:
PYTHON The Label widget is used to display static text or
GUI images in the GUI:

Set label font size:


import tkinter as tk
window = tk.Tk()
window.title("Simple Tkinter Window")
Create First label = tk.Label(window, text="Hello, Tkinter!“
GUI Application , font=("Arial Bold", 50))
Tkinter label.pack() # Positions the label in the window
window.mainloop()

Pr. Mehdia AJANA 7


Tkinter Label Widget:
PYTHON In Tkinter, you can add images to a label using the
GUI PhotoImage class:

Example:
import tkinter as tk
window = tk.Tk()
window.title("Image in Label Example")
Create First # Load an image
GUI Application image = tk.PhotoImage(file="python.png")
Tkinter # Create a label with the image
label = tk.Label(window, image=image)
label.pack()
window.mainloop()

Pr. Mehdia AJANA 8


Tkinter Button Widget:
PYTHON
The Button widget allows the user to trigger an
GUI action, such as a function, when clicked:
Syntax: W = Button(master, options)
window = tk.Tk()
window.title("Simple Tkinter Window")
def on_click(): #Handle button click event
Create First
print("Button clicked!")
GUI Application
button = tk.Button(window, text="Click Me",
Tkinter fg="red", command=on_click) #fg for text color
button.pack() #Places the button in the window.
window.mainloop()

Pr. Mehdia AJANA 9


Tkinter Entry Widget:
PYTHON
The Entry widget is a single-line text input field,
GUI useful for collecting short text input from the user:

Syntax: w = Entry(master, options)


window = tk.Tk()
window.title("Simple Tkinter Window")
Create First entry = tk.Entry(window)
GUI Application entry.pack()
Tkinter window.mainloop()

Pr. Mehdia AJANA 10


Tkinter Text Widget:
PYTHON
The Text widget is a multi-line text input area,
GUI allowing the user to type larger amounts of text:

Syntax: W = Text(master, options)


window = tk.Tk()
window.title("Simple Tkinter Window")
Create First #Create a multi-line text area with specified height
and width.
GUI Application
text = tk.Text(window, height=5, width=20)
Tkinter
text.pack()
window.mainloop()

Pr. Mehdia AJANA 11


Tkinter Checkbutton Widget:
PYTHON
The Checkbutton widget creates a checkbox that
GUI users can select or deselect:

Syntax: w = CheckButton(master, options)


window = tk.Tk()
window.title("Simple Tkinter Window")
Create First checkbutton = tk.Checkbutton(window, text="I
agree")
GUI Application
checkbutton.pack()
Tkinter
window.mainloop()

Pr. Mehdia AJANA 12


Tkinter Checkbutton Widget:
PYTHON
Set check state of a Checkbutton:
GUI Tkinter Variables:
Tkinter provides special variable classes to
manage the values of widgets like Checkbutton
and Radiobutton:
Create First • BooleanVar: Stores True or False.
GUI Application • StringVar: Stores a string value.
Tkinter • IntVar: Stores an integer value.
• DoubleVar: Stores a floating-point value.

Pr. Mehdia AJANA 13


Tkinter Checkbutton Widget:
PYTHON
Set check state of a Checkbutton:
GUI To set the Check State of a Checkbutton:
1. Associate a Variable with the Checkbutton:
Use BooleanVar to represent the
checked/unchecked state of a Checkbutton:
var = tk.BooleanVar()
Create First
2. Set initial state
GUI Application
var.set(True) # Checked by default
Tkinter
3. Create Checkbutton and link it to var
checkbutton = tk.Checkbutton(window,
text="I agree“, variable=var)
checkbutton.pack()
window.mainloop()

Pr. Mehdia AJANA 14


Tkinter Radiobutton Widget:
PYTHON
The Radiobutton widget allows users to select
GUI only one option from the given ones (mutually
exclusive options):
Syntax: W = Radiobutton(master, options)
window = tk.Tk()
window.title("Simple Tkinter Window")
Create First
# Define a variable to group the radiobuttons
GUI Application
selected_option = tk.IntVar() # Holds the value
Tkinter of the selected radiobutton
# Set initial selected option
selected_option.set(2)

15
Tkinter Radiobutton Widget:
PYTHON
The Radiobutton widget allows users to select only
GUI one option from the given ones (mutually exclusive
options):
radio1 = tk.Radiobutton(window, text="Option 1",
value=1, variable=selected_option)
radio2 = tk.Radiobutton(window, text="Option 2",
Create First value=2, variable=selected_option)
GUI Application radio1.pack()
radio2.pack()
Tkinter
window.mainloop()
To get the selected radiobutton value we use:
selected_option.get()

16
Tkinter Scale Widget:
PYTHON
The Scale widget provides a slider that lets users
GUI select a numeric value from a defined range:

Syntax: W = Scale(master, options)


window = tk.Tk()
window.title("Simple Tkinter Window")
scale1 = tk.Scale(window, from_=0, to=100,
Create First orient="horizontal")
GUI Application scale2 = tk.Scale(window, from_=0, to=100,
Tkinter orient="vertical")
scale1.pack()
scale2.pack()
window.mainloop()
#to get the selected
value
scale1.get()

Pr. Mehdia AJANA 17


Tkinter Spinbox Widget:
PYTHON
The Spinbox widget is used to select a value from
GUI the specified given range of values:

Syntax: W = Spinbox(master, options)


window = tk.Tk()
window.title("Simple Tkinter Window")
window.geometry("500x300")
Create First label1 = tk.Label(window, text ='StudyTonight',
GUI Application fg="red",font = "50")
Tkinter label1.pack()
sp = tk.Spinbox(window, from_= 0, to = 10)
sp.pack()
window.mainloop()

Pr. Mehdia AJANA 18


Tkinter Listbox Widget:
PYTHON
The Listbox widget displays a list of items from
GUI which the user can select:
import tkinter as tk
window = tk.Tk()
window.title("Simple Tkinter Window")
listbox = tk.Listbox(window)
listbox.pack()
Create First # Adding items to the listbox
GUI Application listbox.insert(0, "Item 1") #index and string to insert
Tkinter listbox.insert(1, "Item 2")
listbox.insert(2, "Item 3")
window.mainloop()

Pr. Mehdia AJANA 19


Tkinter Menu Widget:
PYTHON The Menu widget is used to create Menus with
GUI options for users to choose from:
Syntax: W = Menu(master, options)
To add an empty menu bar, you can use Menu
class:
menubar = tk.Menu(window)
Create First Then you add labels:
GUI Application menubar.add_command(label="Hello!",
command=hello) #Adding Menu Items to the
Tkinter menubar
menubar.add_command(label="Quit!",
command=window.destroy)
Finally, you assign the menu to the window:
window.config(menu=menubar)

Pr. Mehdia AJANA 20


Tkinter Menu Widget:
PYTHON You can also add a cascading menu under any menu
GUI bar by using add_cascade() function:
In the following example, we will create an
application with a cascading menu:

Create First
GUI Application
Tkinter

Pr. Mehdia AJANA 21


Tkinter Menu Widget:
PYTHON def new_file():
GUI print("New File created!")
def open_file():
print("File opened!")
def exit_app():
window.quit()
Create First
window = tk.Tk()
GUI Application
Tkinter window.title("Simple File Menu Example")
# Creating the main menu
main_menu = tk.Menu(window)
#Adding the menu to the main window
#Attach the main_menu as the main menubar of the
window
window.config(menu=main_menu)
Pr. Mehdia AJANA 22
Tkinter Widgets:
PYTHON The Menu widget:
GUI # Adding a File menu
file_menu = tk.Menu(main_menu, tearoff=0)
main_menu.add_cascade(label="File",
menu=file_menu)
file_menu.add_command(label="New",
command=new_file)
Create First file_menu.add_command(label="Open",
command=open_file)
GUI Application
file_menu.add_separator() # Adds a separator line
Tkinter file_menu.add_command(label="Exit",
command=exit_app)

window.mainloop()

23
Tkinter Frame Widget:
PYTHON The Tkinter Frame widget is an invisible container
GUI used to group and organize the widgets in a better
and friendly way.
The Tkinter frame widget makes up a rectangular
region on the screen.
Syntax: W = Frame(master, options)
Create First Common Options:
• bg: Background color of the frame.
GUI Application
• width: Width of the frame.
Tkinter
• height: Height of the frame.
• relief: Border style (e.g., FLAT, RAISED, SUNKEN,
GROOVE, RIDGE).
• bd: Border width in pixels.

Pr. Mehdia AJANA 24


Tkinter Frame Widget:
PYTHON Example: Create a frame to organize two buttons
GUI # Create main window
window = tk.Tk()
window.title("Frame Example")
window.geometry("200x200")
# Create a frame
Create First frame = Frame(window, bg="lightblue", width=200,
height=100, relief="groove", bd=10)
GUI Application frame.pack(padx=10, pady=10)
Tkinter # Add buttons inside the frame
btn1 = Button(frame, text="Button 1")
btn1.pack(side="left", padx=5, pady=5)
btn2 = Button(frame, text="Button 2")
btn2.pack(side="right", padx=5, pady=5)
# Run the application
window.mainloop()
25
Tkinter Toplevel Widget:
PYTHON The Toplevel widget creates a new window that is
GUI separate from the main application window. It's
useful for personalized dialogs providing extra
information to the user:
import tkinter as tk
def open_toplevel():
top_window = tk.Toplevel(window)
Create First top_window.title("Toplevel Window")
GUI Application label = tk.Label(top_window, text="This is a new
Tkinter Toplevel window")
label.pack()

button_close = tk.Button(top_window,
text="Close",
command=top_window.destroy)
button_close.pack()
Pr. Mehdia AJANA 26
Tkinter Toplevel Widget:
PYTHON #Main window
GUI window = tk.Tk()
window.title("Main Window")
button_open = tk.Button(window, text="Open
Toplevel",
command=open_toplevel)
button_open.pack()
Create First
GUI Application window.mainloop()
Tkinter

Pr. Mehdia AJANA 27


Tkinter Messagebox:
PYTHON
• MessageBox is a module in Tkinter used to
GUI display message boxes to the user.
• It offers various types of message dialogs
which you can combine with user inputs to
create interactive and responsive
applications.
Create First
Method Purpose
GUI Application
showinfo Display informational messages.
Tkinter
showwarning Display warnings to the user.
showerror Display error messages.
askyesno Ask for confirmation (Yes/No).
askretrycancel Ask to retry or cancel an action.

Pr. Mehdia AJANA 28


Common Messagebox Types:
PYTHON Information MessageBox: Displays an informational
GUI message:
from tkinter import messagebox
window = tk.Tk()
window.geometry("200x200")
# Add title and message to be displayed
Create First messagebox.showinfo("Information", "This is an
GUI Application information message.")
Tkinter window.mainloop()

Pr. Mehdia AJANA 29


Common Messagebox Types:
PYTHON Warning MessageBox: Displays a warning message:
GUI
from tkinter import messagebox
window = tk.Tk()
window.geometry("200x200")
# Add title and message to be displayed
Create First messagebox.showwarning("Warning", "This is a
GUI Application warning message!")
Tkinter window.mainloop()

Pr. Mehdia AJANA 30


Common Messagebox Types:
PYTHON Error MessageBox: Displays an error message:
GUI
from tkinter import messagebox
window = tk.Tk()
window.geometry("200x200")
# Add title and message to be displayed
Create First messagebox.showerror("Error", "An error has
GUI Application occurred.")
Tkinter window.mainloop()

Pr. Mehdia AJANA 31


Common Messagebox Types:
PYTHON Yes/No Confirmation MessageBox: Asks the user to
GUI confirm an action:
from tkinter import messagebox
window = tk.Tk()
window.geometry("200x200")
response = messagebox.askyesno("Confirmation",
Create First "Are you sure you want to delete this file?")
GUI Application if response:
Tkinter print("File deleted.")
else:
print("Action canceled.")
window.mainloop()

Pr. Mehdia AJANA 32


Common Messagebox Types:
PYTHON Retry/Cancel MessageBox: Asks the user to retry or
GUI cancel an action:
from tkinter import messagebox
window = tk.Tk()
window.geometry("200x200")
response = messagebox.askretrycancel("Retry", "Do
Create First you want to try again?")
GUI Application if response:
Tkinter print("Retrying...")
else:
print("Operation canceled.")
window.mainloop()

Pr. Mehdia AJANA 33


Tkinter Layout/Geometry Managers:
PYTHON Layout managers control widget placement in
GUI Tkinter applications.

Each window and Frame in your application is


allowed to use only one layout manager.

Different frames can use different layout managers,


even if they're already assigned to a frame or
Create First window using another geometry manager.
GUI Application
The three main layout managers are:
Tkinter
1. pack: Organizes widgets in a block, placing them
top-to-bottom (default) or side-by-side.
2. grid: Places widgets in a table-like structure with
rows and columns.
3. place: Allows exact positioning by specifying x
and y coordinates.

Pr. Mehdia AJANA 34


The pack() Layout Manager:
PYTHON The pack() manager places widgets in a
GUI sequence, either vertically or horizontally.
Options:
• side: Sets widget position (top, bottom, left,
right).
• fill: Expands widget to fill space (x, y, both).
• expand: Expands widget to fill unused space if
Create First True.
GUI Application Example 1: pack() three colored Frame widgets:
Tkinter The pack() method just places each Frame below the
previous one by default, in the same order in which
they're assigned to the window.

Pr. Mehdia AJANA 35


The pack() Layout Manager:
PYTHON Example 2: pack() with Parameters:
GUI 3 frames filling the whole window horizontally:
The frames fill the entire width of the
application window because we used the “x”
value for the fill parameter.

Create First
GUI Application
Tkinter

Pr. Mehdia AJANA 36


The grid() Layout Manager:
PYTHON The grid() manager organizes widgets in a table-like
GUI grid using rows and columns.
Options:
• row and column: Specify widget position.
• rowspan and columnspan: Span across multiple
rows/columns.
• padx and pady: Add padding/space around
Create First widgets.
GUI Application Example:
Tkinter import tkinter as tk
window = tk.Tk()
label1 = tk.Label(window, text="Row 0, Col 0",
bg="lightblue")
label1.grid(row=0, column=0, padx=5, pady=5)

Pr. Mehdia AJANA 37


The grid() Layout Manager:
PYTHON Example (continued):
GUI label2 = tk.Label(window, text="Row 0, Col 1",
bg="lightgreen")
label2.grid(row=0, column=1, padx=5, pady=5)
label3 = tk.Label(window, text="Row 1, Col 0",
bg="lightcoral")
label3.grid(row=1, column=0, columnspan=2,
Create First padx=5, pady=5)
GUI Application window.mainloop()
Tkinter

Pr. Mehdia AJANA 38


The place() Layout Manager:
PYTHON The place() manager allows precise control by
GUI setting exact x and y coordinates.
Options:
• x and y: Specify exact position within the window.
Example:
import tkinter as tk
window = tk.Tk()
Create First label = tk.Label(window, text="Exact Position",
GUI Application bg="lightblue")
# x is distance from the left
Tkinter # y is distance from the top
label.place(x=50, y=50)
window.mainloop()

Pr. Mehdia AJANA 39


Widget Customization Options:
PYTHON
Tkinter widgets come with various options for
GUI customization, including colors, fonts, size, and
more.
Common Options:
• bg and fg: Background and foreground (text)
colors.
Create First • font: Font style, size, and weight.
GUI Application • width and height: Specify dimensions.
Tkinter • padx: Adds extra space on the left and right sides
of the widget.
• pady: Adds extra space on the top and bottom of
the widget.

Pr. Mehdia AJANA 40


Widget Customization Options:
PYTHON Example: customizing the Label and Button widgets
GUI with colors, font, and padding:
import tkinter as tk
window = tk.Tk()
label = tk.Label(window, text="Customized Label",
bg="red", fg="blue", font=("Arial", 16, "bold"))
label.pack(padx=30,pady=30)
Create First
button = tk.Button(window, text="Customized
GUI Application Button", bg="lightgray", fg="green",
Tkinter font=("Helvetica", 12))
button.pack()
window.mainloop()

Pr. Mehdia AJANA 41


Event Management in Tkinter GUI:
PYTHON
Event management allows Tkinter applications
GUI to respond to user actions, like clicks, key
presses, and more.
Events: Tkinter supports various events,
including:

Create First • Button Clicks


GUI Application • Key Presses
Tkinter • Mouse Movements
Binding Functions: Link events to functions
whenever an event occurs, making the
application interactive.

Pr. Mehdia AJANA 42


Button Click Event:
PYTHON
Button clicks are one of the most common
GUI events in GUIs, often used to trigger actions.
Example:
import tkinter as tk
def on_click():
print("Button was clicked!")
window = tk.Tk()
Create First button = tk.Button(window, text="Click Me",
GUI Application command=on_click)
Tkinter button.pack()
window.mainloop()

command=on_click: Links the button to the


on_click function, which is executed when the
button is clicked.
Button was clicked!

Pr. Mehdia AJANA 43


Keyboard Event Handling:
PYTHON
Captures keyboard events, allowing the program to
GUI respond to specific keys.
Example:
import tkinter as tk
def on_key(event):
print("Key pressed:", event.char)

Create First window = tk.Tk()


GUI Application window.bind("<Key>", on_key)
Tkinter window.mainloop() Key pressed: a

window.bind("<Key>", on_key): Attaches an event


handler to the root window: Links any key press
(type of event) to the on_key function.
Event handler function: function to call when the
event occurs
event.char: Provides the character of the key
pressed.
Pr. Mehdia AJANA 44
Mouse Click Event:
PYTHON
Detects mouse clicks on the window, which can
GUI be used for various interactions, like selecting
items.
The three major mouse click events are:

Create First
GUI Application
Tkinter

Pr. Mehdia AJANA 45


Mouse Click Event:
PYTHON Example: Left mouse click
GUI import tkinter as tk

def on_mouse_click(event):
print("Mouse clicked at:", event.x, event.y)

window = tk.Tk()
Create First
window.bind("<Button-1>", on_mouse_click)
GUI Application # Left-click
Tkinter window.mainloop()

bind("<Button-1>", on_mouse_click): Detects a


left mouse click anywhere in the window.
event.x and event.y: Capture the x and y
coordinates of the click.
Mouse clicked at: 101 108
Pr. Mehdia AJANA 46
Mouse Motion Event:
PYTHON
Tracks mouse movement within the window, which
GUI can be useful for interactive applications.
Example:
import tkinter as tk
def on_mouse_move(event):
print("Mouse moved to:", event.x, event.y)
window = tk.Tk()
Create First window.bind("<Motion>", on_mouse_move)
GUI Application window.mainloop() Mouse moved to: 155 177
Tkinter Mouse moved to: 150 162
Mouse moved to: 146 153
Mouse moved to: 142 143
…………….

bind("<Motion>", on_mouse_move): Tracks any


mouse movement within the window.
event.x and event.y: Capture the current mouse
position. Pr. Mehdia AJANA 47
Combining Events with Widgets:
PYTHON Events can be combined with widgets for more
GUI interactive applications.
Example: a user enters text into an Entry widget,
and upon clicking a Button, the Label updates to
display the entered text:
import tkinter as tk
def update_label():
Create First # Get text from entry widget and set it as the label
text
GUI Application
entered_text = entry.get()
Tkinter label.config(text=f"You entered: {entered_text}")

window = tk.Tk()
# Label to display the text
label = tk.Label(window, text="Enter text and click
the button")
label.pack(pady=10)

Pr. Mehdia AJANA 48


Combining Events with Widgets:
PYTHON Example (continued):
GUI # Entry widget for text input
entry = tk.Entry(window)
entry.pack(pady=5)

# Button to trigger label update


Create First button = tk.Button(window, text="Update Label",
command=update_label)
GUI Application
button.pack(pady=5)
Tkinter
window.mainloop()

Pr. Mehdia AJANA 49


Combining Events with Widgets:
PYTHON Another Example of Login Form:
GUI Check TkinterLecture.py file

Create First
GUI Application
Tkinter

Pr. Mehdia AJANA 50


Introduction to C++:
PYTHON What is C++?
vs. C++ • Developed by Bjarne Stroustrup in 1983.
• A high-performance, general-purpose
programming language.
• It is a compiled and strongly typed
programming language.
Introduction to • Based on C with added support for Object-
Oriented Programming (OOP).
C++
• It supports both procedural and object-
oriented paradigms.
• It is Extensively used in game development,
operating systems, and embedded systems.
• There exists multiple C++ IDEs: the
Recommended ones are :Visual Studio
(Windows), and Code::Blocks (Cross-
platform). Pr. Mehdia AJANA 51
Introduction to C++:
PYTHON Compiled vs Interpreted Languages:
vs. C++ Compiled Languages (e.g., C++)
• Source code is translated into machine code
(binary format) using a compiler.
• Faster execution.
• Errors detected before running the program.
Introduction to • Requires recompilation for changes.
C++ Interpreted Languages (e.g., Python)
• Source code is executed line-by-line by an
interpreter.
• Slower execution.
• Errors detected during runtime.

Pr. Mehdia AJANA 52


C++ Syntax Basics:
PYTHON
#include <iostream> // Header file/library for
vs. C++ input/output
using namespace std; // Simplifies syntax
int main() { //Entry point of the program
// use std::cout if namespace is not included
cout << "Hello, World!"; // Console output:
Introduction to Print statement
C++ return 0; // Return 0 to indicate successful
execution
}
Python Equivalent:
print("Hello, World!")

Pr. Mehdia AJANA 53


Variables and Data Types:
PYTHON
• Static vs. dynamic typing.
vs. C++ • Data types must be explicitly declared in C++.
C++ Example:
int age = 25; // Integer
double pi = 3.14; // Floating-point
char grade = 'A'; // Character
Introduction to
string name = "Alice"; // String
C++
Python Equivalent:
age = 25 # Integer
pi = 3.14 # Floating-point
grade = 'A' # Character as a string
name = "Alice" # String

Pr. Mehdia AJANA 54


User Input and Control Flow:
PYTHON C++ Example:
vs. C++ #include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: "; // << insertion
operator
cin >> number; // >> extraction operator: read
Introduction to entered value into number variable
C++ if (number > 0) {
cout << "Positive number.\n";
} else {
cout << "Non-positive number.\n";
}
for (int i = 1; i <= number; i++) {
cout << i << " ";
}
return 0;
} Pr. Mehdia AJANA 55
User Input and Control Flow:
PYTHON Python Equivalent:
vs. C++ number = int(input("Enter a number: "))
if number > 0:
print("Positive number.")
else:
print("Non-positive number.")
Introduction to
C++ for i in range(1, number + 1):
print(i, end=" ")

Pr. Mehdia AJANA 56


Function Comparison: Python vs. C++:
PYTHON C++ Example:
vs. C++ • Functions require a return type (e.g., int,
void).
• Parameters must have explicit data types.
#include <iostream>
using namespace std;
Introduction to // Function definition
C++ int addNumbers(int a, int b) {
return a + b;
}
int main() {
int result = addNumbers(5, 10);
cout << "Sum: " << result;
return 0;
}
Pr. Mehdia AJANA 57
Function Comparison: Python vs. C++:
PYTHON Python Example:
vs. C++ • No need to specify return types or
parameter types.
# Function definition
def add_numbers(a, b):
return a + b
Introduction to # Function call
C++ result = add_numbers(5, 10)
print("Sum:", result)

Pr. Mehdia AJANA 58


Key Differences in OOP:
PYTHON C++ Class:
vs. C++ class Person {
public:
string name;
int age;
void display() {
cout << "Name: " << name << ", Age: " <<
Introduction to age;
}
C++ };
int main() { // Instantiate objects
Person person1;
person1.name = "Ali";
person1.age = 25;
person1.display(); Name: Ali, Age: 25
return 0;
} Pr. Mehdia AJANA 59
Key Differences in OOP:
PYTHON Python Class:
vs. C++ class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
Introduction to print(f"Name: {self.name}, Age:
C++ {self.age}")
# Instantiate objects
person1 = Person("Ali", 25) # Object with name
and age
person1.display() Name: Ali, Age: 25

Pr. Mehdia AJANA 60


Python vs. C++:
PYTHON Feature Python C++

vs. C++ Type System Dynamically typed


Easy to read, simple,
Statically typed
Complex, Strict,
Syntax fewer rules and lines of semicolon-based,
code long lines of code
Execution Interpreted Compiled
Slower (due to
Faster (compiled to
interpretation) and also
Speed machine code before
determines the data type
execution)
Introduction to at run time
Extensive libraries but
C++ Libraries Rich built-in libraries more manual
integration
Game Dev, System
Web development, data Programming (with
Application
analysis, scientific hardware
Domain
computations, AI Interactions),
Embedded Systems
Python programs are C++ programs are
Extension saved with the .py saved with the .cpp
extension extension
Pr. Mehdia AJANA 61
References:
PYTHON Python Tkinter:
vs. C++ • https://www.geeksforgeeks.org/python-gui-
tkinter/#tkinter-widget
• https://www.studytonight.com/tkinter/
• https://www.studytonight.com/tkinter/python-
tkinter-widgets
• https://www.edureka.co/blog/tkinter-tutorial/
Introduction to Introduction to C++:
C++ • https://www.w3schools.com/cpp/cpp_intro.asp
• https://www.tutorialspoint.com/cplusplus/cpp_o
verview.htm
• https://www.geeksforgeeks.org/difference-
between-python-and-c/

Pr. Mehdia AJANA 62

You might also like