Python 5
Python 5
server_socket.bind(('localhost', 12345))
server_socket.listen(1)
print("Server is listening on port 12345...")
data = client_socket.recv(1024).decode()
print("Received from client:", data)
client_socket.close()
server_socket.close()
2] Client Program (client.py)
import socket
client_socket.connect(('localhost', 12345))
response = client_socket.recv(1024).decode()
print("Received from server:", response)
client_socket.close()
Output:
Server Side
Server is listening on port 12345...
Connection from ('127.0.0.1', 56789) has been established!
Received from client: Hello Server, this is Client!
Client Side
Received from server: Hello Client, message received.
Q2] Explain what Tkinter is and how it is used to create GUI applications in Python.
Demonstrate with a simple window creation program.
Tkinter is the standard Graphical User Interface (GUI) library included with Python. It
provides tools to build desktop applications with windows, buttons, labels, text fields, and
other interactive components.
Key Features of Tkinter:
1] Built-in and cross-platform: Works on Windows, macOS, and Linux.
2] Widget-based: Provides various GUI widgets like Label, Button, Entry, Text, Canvas,
Frame, etc.
3] Event-driven: Handles user interactions via events (like button clicks).
4] Layout Management: Uses pack(), grid(), and place() to arrange widgets.
5] Customizable: Allows setting fonts, colors, sizes, and styles.
6] Lightweight: Comes pre-installed with Python; no need to install separately.
7] Suitable for small to medium applications: Ideal for educational tools, form applications,
etc.
Steps to Create a Tkinter GUI Window:
1] Import the tkinter module.
2] Create a main window using Tk().
3] Add widgets (like labels, buttons, etc.).
4] Use layout managers to position widgets.
5] Run the event loop using mainloop().
Example: Simple Window Creation Program
import tkinter as tk
root = tk.Tk()
root.mainloop()
Q3] Explain how do you add widgets such as labels, buttons, and text entries in a Tkinter
window? Demonstrate with a sample program.
Steps to Add Widgets in Tkinter:
1] Import the tkinter module.
2] Create the main window using Tk().
3] Create widgets like Label(), Button(), and Entry().
4] Place widgets using pack(), grid(), or place().
5] Start the GUI event loop with mainloop().
Sample Program: Adding Label, Button, and Entry Widgets
import tkinter as tk
root = tk.Tk()
root.title("Student Info")
root.geometry("300x200")
entry = tk.Entry(root)
entry.pack(pady=5)
def greet_user():
name = entry.get()
result_label.config(text=f"Hello, {name}!")
root.mainloop()
Output:
A GUI window appears with:
A prompt to enter a name
An input field
A submit button
A greeting displayed after clicking the button
Q4] Explain Combo box widget with the help of example.
A Combo Box (short for combination box) is a widget in Tkinter that provides a drop-down
menu from which the user can select one option. It combines a text box with a listbox,
allowing both selection and text entry.
In Tkinter, the Combobox widget is available in the ttk (Themed Tkinter) module.
Significance of Combobox:
1] Allows users to select from a list of predefined values.
2] Improves user experience by reducing typing effort.
3] Useful for forms like country selection, gender, course names, etc.
4] Can also allow manual input if configured.
Example: ComboBox in Student Course Selection
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Course Selection")
root.geometry("300x200")
root.mainloop()
Output:
A GUI window with:
A dropdown list of courses
A Submit button
A label that shows the selected course after clicking the button
def on_click():
print("Button was clicked!")
root = tk.Tk()
button = tk.Button(root, text="Click Me", command=on_click)
button.pack()
root.mainloop()
2] Key Press (Keyboard Binding)
You can bind a function to key press events using the bind() method with <Key> or specific
key tags.
def key_pressed(event):
print(f"Key pressed: {event.char}")
root.bind("<Key>", key_pressed)
3] Mouse Movement or Click
You can track mouse movement with <Motion> or detect mouse button clicks using
<Button-1>, <Button-2>, or <Button-3>.
def mouse_click(event):
print(f"Mouse clicked at: {event.x}, {event.y}")
root.bind("<Button-1>", mouse_click)
Example: Handling Multiple Events
import tkinter as tk
def on_button_click():
print("Button clicked!")
def on_key(event):
print("Key:", event.char)
def on_mouse_move(event):
print(f"Mouse at: {event.x},{event.y}")
root = tk.Tk()
button = tk.Button(root, text="Click Me", command=on_button_click)
button.pack()
root.bind("<Key>", on_key)
root.bind("<Motion>", on_mouse_move)
root.mainloop()
Q7] Explain the difference between TCP and UDP protocols in Python networking.
TCP (Transmission Control UDP (User Datagram
Feature
Protocol) Protocol)
Connection-oriented
Connectionless (no need to
Connection Type (requires connection before
establish a connection)
data transfer)
Reliable – ensures delivery,
Unreliable – no guarantee of
Reliability sequencing, and error
delivery or order
checking
Slower due to overhead of
Faster due to minimal
Speed connection and
overhead
acknowledgments
Message-based (data sent in
Stream-based (continuous
Data Transmission individual
flow of data)
packets/datagrams)
Performs error checking and Performs basic error
Error Handling
correction checking (no correction)
Web browsing, email, file Live video streaming,
Use Cases
transfer (HTTP, SMTP, FTP) gaming, VoIP
Python Socket Type socket.SOCK_STREAM socket.SOCK_DGRAM
server_socket.bind(('localhost', 12345))
server_socket.listen(1)
print("Server is listening...")
data = client_socket.recv(1024)
print("Received message from client:", data.decode())
client_socket.send(b"Hello from server!")
client_socket.close()
server_socket.close()
2] TCP Client Program:
import socket
client_socket.connect(('localhost', 12345))
client_socket.send(b"Hello Server!")
data = client_socket.recv(1024)
print("Received message from server:", data.decode())
client_socket.close()
Output:
Server Output:
Server is listening...
Connection established with ('127.0.0.1', 54684)
Received message from client: Hello Server!
Client Output:
Received message from server: Hello from server!
Q12] Explain Layout Management in detail.
Layout management in Tkinter is a mechanism that controls the placement of widgets
within a window. It helps in organizing and arranging the widgets (such as buttons, labels,
text fields) in a visually appealing and functional manner. Tkinter provides several layout
management methods to position the widgets effectively and resize them automatically
when the window is resized.
Types of Layout Managers in Tkinter:
Pack
Grid
Place
1] Pack Layout Manager:
The pack() method is the simplest and most commonly used layout manager. It organizes
widgets in blocks or stacks, placing them from top to bottom or left to right.
Key Options in pack() Method:
A] side: Determines the side of the parent widget where the widget should be placed (TOP,
BOTTOM, LEFT, RIGHT).
B] fill: Determines how the widget should expand to fill space (NONE, X, Y, BOTH).
C] expand: When set to True, it allows the widget to expand and occupy any extra space in
the parent widget.
2] Grid Layout Manager:
The grid() method places widgets in a table-like structure, where each widget is positioned
in a specific row and column.
Key Options in grid() Method:
A] row: Specifies the row in which the widget should appear.
B] column: Specifies the column in which the widget should appear.
C] sticky: Determines how the widget should stretch to fill its cell (e.g., N, S, E, W for North,
South, East, West).
D] rowspan: Specifies how many rows the widget should span.
E] columnspan: Specifies how many columns the widget should span.
3] Place Layout Manager:
The place() method allows for precise placement of widgets by specifying the x and y
coordinates, and other positioning options like width and height.
Key Options in place() Method:
A] x, y: Specify the position of the widget in pixels relative to the parent window.
B] relx, rely: Specify the position as a percentage (0.0 to 1.0) of the parent window’s size.
C] width, height: Set the widget’s size explicitly.
D] anchor: Determines how the widget is aligned in the specified position (N, E, S, W).
Q13] Explain the concept of drawing, how we can draw on Canvas in python.
Drawing in Python, especially in GUI applications, can be done using the Canvas widget
from the Tkinter library. The Canvas widget allows you to draw shapes, lines, text, and even
images directly onto a window. This is particularly useful when creating custom graphics,
games, or interactive user interfaces.
The Canvas widget provides a variety of methods to draw and manipulate shapes, and it is
widely used in applications where custom graphical content is required.
Canvas Widget in Tkinter:
The Canvas widget is a blank area where you can draw shapes, display images, or create
custom graphics. It provides various methods for drawing:
Creating lines, rectangles, ovals, polygons, and text.
Handling events like mouse clicks or movements.
Displaying images or custom graphics.
Basic Usage of Canvas:
To use the Canvas widget, you need to:
1] Create an instance of the Canvas widget.
2] Place it within a parent widget or the main window.
3] Use various drawing methods to add shapes, lines, and images.
Basic Drawing Methods on Canvas:
1] create_line(x1, y1, x2, y2, options): Draws a line from (x1, y1) to (x2, y2).
2] create_rectangle(x1, y1, x2, y2, options): Draws a rectangle from top-left (x1, y1) to
bottom-right (x2, y2).
3] create_oval(x1, y1, x2, y2, options): Draws an oval inside the bounding box defined by
(x1, y1) and (x2, y2).
4] create_text(x, y, text, options): Adds text at the position (x, y).
Manipulating Objects:
Once a shape is drawn on the canvas, it can be manipulated further using its object ID
returned by the drawing methods. This allows you to modify or delete objects after they
have been created.
For example:
1] item.config(options): Modify properties of an object.
2] canvas.delete(object_id): Deletes the object from the canvas.
Q14] Describe Tkinter library with example.
Tkinter is the standard Python library used for building Graphical User Interfaces (GUIs). It
provides tools for creating desktop applications with windows, buttons, labels, text entries,
and other common GUI components. Tkinter is a thin object-oriented layer on top of the Tk
GUI toolkit, which is widely used for creating cross-platform applications in Python. Tkinter
allows Python programmers to easily create windows, dialogs, and other user interface
components, making it ideal for building interactive applications.
Common Tkinter Widgets:
1] Label: Displays text or images.
2] Button: Triggers a function or action when clicked.
3] Entry: Allows the user to input text.
4] Text: A widget for multi-line text input.
5] Frame: A container widget to organize other widgets.
6] Canvas: Used for drawing graphics and handling custom graphics.
7] Checkbutton: A checkbox widget that can be toggled on or off.
8] Radiobutton: A button that represents a choice in a group of options.
Example Program: Creating a Basic Tkinter Window with Widgets
import tkinter as tk
def display_message():
name = entry.get()
label.config(text=f"Hello, {name}!")
root = tk.Tk()
root.title("Tkinter Example")
root.geometry("300x200")
root.mainloop()
Q16] Explain the concept of Networking in python. Write a program to identify the IP
address of a current system.
Networking in Python refers to the process of connecting computers or devices to exchange
data over a network, typically using the Internet or a Local Area Network (LAN). Python
provides multiple libraries to work with network-related tasks, such as socket programming,
working with IP addresses, creating servers and clients, sending and receiving data, and
more. The core library for networking in Python is the socket module, which allows the
development of both client and server applications.
Key Networking Concepts in Python:
1] Socket Programming: In Python, a socket is an endpoint for sending or receiving data
across a computer network. Socket programming allows the development of
communication protocols and networking services.
2] Client-Server Model: This is a common networking model where the client sends
requests and the server processes those requests and returns the response.
3] IP Address: Every device on a network is assigned a unique identifier known as an IP
address. In networking, IP addresses are used to route data between different devices.
4] Ports: A port is an endpoint for communication, and different ports are used for various
services, like HTTP (port 80), HTTPS (port 443), etc.
Example Program to Identify the IP Address of the Current System:
import socket
def get_ip_address():
host_name = socket.gethostname()
ip_address = socket.gethostbyname(host_name)
return ip_address
ip = get_ip_address()
print(f"The IP address of this system is: {ip}")