Mod 5
Mod 5
Assistant Professor
SCSE, VIT Bhopal
2. mainloop()
Creating the Python application with GUI
• Tk(screenName=None, baseName=None, className=’Tk’,
useTk=1):
To create a main window, tkinter offers a method
‘Tk(screenName=None, baseName=None, className=’Tk’, use
Tk=1)’.
To change the name of the window, you can change the
className to the desired one.
The basic code used to create the main window of the
application is
Creating the Python application with GUI
• There is a method known by the name mainloop() is used when
your application is ready to run.
• The mainloop() 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 not closed.
m.mainloop()
Geometry manager classes
Tkinter also offers access to the geometric configuration of the
widgets which can organize the widgets in the parent windows.
There are mainly three geometry manager classes class.
1.pack() method:It organizes the widgets in blocks before
placing in the parent widget.
2.grid() method:It organizes the widgets in grid (table-like
structure) before placing in the parent widget.
3.place() method:It organizes the widgets by placing them on
specific positions directed by the programmer.
• GUI stands for Graphical User Interface, which is
a way of interacting with a computer program
using graphical elements, such as windows,
buttons, menus, icons, etc.
INTRODUCTION
Tkinter PyQT
-Tkinter is Python’s standard GUI framework, which is based on the Tk • PyQt is a cross-platform GUI
toolkit framework, which is based on the
Qt toolkit
-Tkinter is simple and easy-to-use, and it comes pre-installed with Python
• PyQt is powerful and feature-rich,
-Tkinter is based on the Tcl/Tk scripting language, which is a cross- and it requires installation and
platform, dynamic, and embeddable language licensing
⚬ Event loop: A loop that waits for user events, such as mouse clicks or
keyboard presses, and executes the corresponding event handlers
Widgets and Events
• Widgets are the basic building blocks of a GUI application, such as buttons, labels,
entries, etc
• To create and configure widgets using Tkinter, you need to instantiate the widget
class and pass the parent window and other options as arguments
• To arrange widgets in a window, you need to use one of the geometry managers:
pack, grid, or place
• Events are the actions that occur when a user interacts with a GUI application, such as clicking a button, typing a
key, moving the mouse, etc
• To bind events to widgets using Tkinter, you need to use the bind method and pass the event type and the event
handler as arguments
• To write event handlers or callback functions, you need to define a function that takes an event object as a
parameter and performs some actions
Widgets and Events
• Widgets are the basic building blocks of a GUI application, such as buttons, labels,
entries, etc
• To create and configure widgets using Tkinter, you need to instantiate the widget
class and pass the parent window and other options as arguments
• To arrange widgets in a window, you need to use one of the geometry managers:
pack, grid, or place
• Events are the actions that occur when a user interacts with a GUI application, such as clicking a button, typing a
key, moving the mouse, etc
• To bind events to widgets using Tkinter, you need to use the bind method and pass the event type and the event
handler as arguments
• To write event handlers or callback functions, you need to define a function that takes an event object as a
parameter and performs some actions
import tkinter as tk • The code imports the
from tkinter import simpledialog modules, defines a function to
check the answer, creates a
def check_answer():
window and a button, and
answer = simpledialog.askstring("Question", "Which college has the worst management?")
runs the loop
Example
EVENT DRIVEN PROGRAMMING
In computer programming, event-
driven programming is a
programming paradigm in which the
flow of the program is determined by
external events. Event-driven In an event-driven application, there is generally an
event loop that listens for events and then triggers a
programming is the dominant callback function when one of those events is
paradigm used in graphical user detected.
Let's go!
Coroutines are functions which can pause for an
input during its execution. They are similar to
python generators but unlike generators which
pauses to send result back to caller, coroutines
pauses to accept inputs from caller.
Next
This Python program employs the asyncio module to showcase
asynchronous programming. It defines two tasks with sleep periods, runs
them concurrently in the main coroutine, and prints messages indicating
their start and completion. The output demonstrates the asynchronous
nature, with the shorter task finishing first, followed by the longer one,
and the main coroutine concluding after awaiting both tasks.
With `send`, values can be sent into the generator/coroutine, causing it to resume
execution from the `yield` point. This mechanism facilitates cooperative multitasking and
efficient communication between different parts of a program.
This Python code defines two coroutines,
`coroutine_one` and `coroutine_two`, which
communicate cooperatively using the `yield` and
`send` mechanism. The coroutines take turns
executing, with Coroutine One starting first,
yielding, receiving a value from Coroutine Two,
yielding another message, and then completing.
Coroutine Two starts, yields, resumes after Coroutine One's initial yield,
sends a message to Coroutine One, receives a response, and then
completes
Creating and Scheduling Tasks
Tasks in Python's asyncio are objects that wrap coroutines and manage their
execution.
The asyncio module provides the necessary tools for creating, scheduling, and
managing tasks to achieve concurrent execution in Python applications.
Creating and Scheduling Tasks
Tasks can be managed by using the task.cancel() method to cancel a task's execution.
Additionally, tasks can be awaited using the await keyword for synchronization, allowing
for coordination between different tasks. This enables tasks to run in parallel, achieving
concurrent execution and efficient utilization of system resources.
When working with asyncio tasks, it is important to follow best practices for managing and
organizing tasks within asyncio applications. This includes proper error handling, graceful
cancellation of tasks, and efficient resource management. Leveraging asyncio tasks effectively
in Python applications offers benefits such as improved performance, scalability, and
responsiveness.
Event Loop
This code will run the synchronous my_function in the default event
loop using asyncio.run().
There are a number of widgets which you can put in your tkinter application. Some
of the major widgets are explained below:
• Button: • MenuButton:
• Canvas: • Menu:
• CheckButton: • Message
• Entry • RadioButton:
• Frame • Scale:
• Label: • Scrollbar:
• Listbox: • Text:
• SpinBox:
• PannedWindow
Button
Button: To add a button in your application, this widget is used. Master is the parameter used to represent the parent
window.
The general syntax is
:w=Button(master, option=value) There are number of options which are used to change
the format of the Buttons.
Number of options can be passed as parameters
separated by commas. Some of them are listed below.
• activebackground: to set the background color
when button is under the cursor.
• activeforeground: to set the foreground color when
button is under the cursor.
• bg: to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the button.
• width: to set the width of the button.
• height: to set the height of the button
Canvas:
• Canvas is used to draw pictures and other complex layout like
graphics, text and widgets. The general syntax is
Canvas
Number of options can be passed as parameters separated by
commas. Some of them are listed below.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used in the canvas.
• highlightcolor: to set the color shown in the focus highlight.
• width: to set the width of the widget.
• height: to set the height of the widget.
Frame:
• Frame acts as a container to hold the widgets. It is used for
grouping and organizing the widgets.
The general syntax is:
w = Frame(master, option=value)
master is the parameter used to represent the parent
window.
Options can be passed as parameters
• There are number of options which are used to change the format of
the widget. Number of options can be passed as parameters
separated by commas. Some of them are listed below.
• highlightcolor: To set the color of the focus highlight when widget
has to be focused.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• width: to set the width of the widget.
• height: to set the height of the widget.
Label Widget
A button is a clickable element that triggers an action when pressed. It is often labeled with
Buttons
text or an icon.
Entry An entry widget is a text box that allows users to input single-line text data.
Text Similar to an entry widget, a text widget allows users to input and display multiline text.
Labels are used to display text or images and provide information to the user. They are
Label
typically non-interactive.
WIDGETS (CONT.)
Widget Description
Radiobuttons are used in groups where only one option can be selected at a time. They are
Radiobutton
often used for mutually exclusive choices.
A listbox is a widget that displays a list of items, and users can select one or more items
Listbox
from the list.
Scrollbars are used to navigate through content that doesn't fit within the visible area of a
Scrollbar
widget, such as a text box or listbox.
A canvas widget provides an area for drawing shapes, lines, and images. It is useful for
Canvas
creating custom graphics.
Menus and menu items are used to organize and present a set of commands or options to
Menu
the user.
pAck()
GEOMETRIC Organizes the widgets in blocks .
CONFIGURATION
Tkinter offers access to the geometric Grid()
configuration of the widgets which can organize Organizes the widgets in grid
the widgets in the parent windows. There are (table?like structure) .
mainly three geometry manager classes class.
Places()
Organizes the widgets by placing them
on specific positions.
Back to Index Page
Back to Index Page
TKINTER
EXAMPLES
#CALCULATOR
In this approach, we write the code with .py extension, which can be
then reference in the <py-script> tag using the src attribute.
IP Address
An Internet Protocol (IP) address is a unique numerical identifier for every device or network
that connects to the internet. Typically assigned by an internet service provider (ISP), an IP
address is an online device address used for communicating across the internet.
192.168.0.104 103.227.99.252
(host) (host)
Port
A list of some important modules in Python Network/Internet programming
Sockets: Sockets serve as communication endpoints that allow bidirectional data flow
between different processes, either on the same machine or across a network. They
facilitate the establishment of connections, transmission, and reception of data
between a client and a server.
PROGRAMMING Python's Socket Module: Python provides a robust socket module that simplifies
socket programming. This module abstracts underlying complexities and provides a
set of functions and methods for creating and managing sockets.
Functions and Methods: Python's socket module includes various functions and
methods such as socket(), bind(), listen(), accept(), connect(), send(), and
recv(), among others. These functions enable developers to create sockets, establish
connections, send and receive data, and manage socket-related operations
INTRODUCTION TO
CLIENT/SERVER
ARCHITECTURE
Client/server architecture is a foundational model in computing, establishing a
structured approach for distributed applications. It comprises two distinct entities –
the client, which requests services or resources, and the server, which provides
these services or resources in response to client requests.
In this architecture, clients and servers communicate over a network using protocols
(such as HTTP, TCP/IP, or UDP) to exchange data. The client initiates a request,
transmitting it to the server, which processes the request and responds accordingly.
This interaction forms the basis for various network-based applications and services
across different domains.
SETTING UP A SERVER AND CLIENT IN
PYTHON
Server Setup with Python's Socket Module
● Steps:
● Create a server socket using Python's socket module.
● Bind the server socket to an address/port.
● Listen for incoming connections using listen().
</body>
</html>
<head>....</head>
<!DOCTYPE html>
Contains metadata and <html>
HTML comes with the support of a vast collection of libraries which serve for
various purposes, making our programming experience smoother and
enjoyable.
USING
Python programs are used for:
With this said, let us see how we can use python programs to
generate HTML files as output. This is very effective for those
programs which are automatically creating hyperlinks and graphic
entities.
CREATING A HTML FILE
IN PYTHON
We will be storing HTML tags in a multi-line Python
string and saving the contents to a new file. This file
will be saved with a .html extension rather than a
.txt extension.
VIEWING THE HTML
SOURCE FILE
In order to display the HTML file as a python output, we
will be using the codecs library. This library is used to
open files which have a certain encoding. It takes a
parameter encoding which makes it different from the
built-in open() function. The open() function does not
contain any parameter to specify the file encoding.
VIEWING THE HTML WEB
FILE
In Python, webbrowser module provides a high-
level interface which allows displaying Web-based
documents to users. The webbrowser module can be
used to launch a browser in a platform-independent
manner as shown below:
• A remote HTML server is a server that hosts HTML files and serves them to
What is a clients over the internet.
Remote HTML • It allows developers to store and access their HTML files remotely, without
Server? the need for local hosting.
• Ease of access: Developers can access their HTML files from anywhere with an internet
Benefits of a connection.
Remote HTML • Collaboration: Multiple developers can work on the same HTML files simultaneously, facilitating
Server collaboration.
• Scalability: Remote HTML servers can handle high traffic and accommodate increasing demands.
Client and Server Side Technologies
Interacting with a remote HTML server involves a combination of client-side technologies and server-side technologies.
Client-Side Technologies-Responsible for rendering and interacting with the user interface
• HTML (Hypertext Markup Language)-Defines the structure and content of the web page.
• CSS (Cascading Style Sheets)-Defines the presentation and layout of the HTML elements.
• JavaScript- Enables dynamic and interactive behavior on the client side,Can be used to make asynchronous requests to the
server.
Server-Side Technologies-handle processing requests, managing data, and sending responses back to the client.
• Server-The server handles incoming requests from clients and sends back responses.Common server technologies include
Apache, Nginx, or Microsoft Internet Information Services (IIS).
• Server-Side Scripting Languages-PHP, Python (Django, Flask), Ruby (Ruby on Rails), Node.js (JavaScript on the server), Java
(Servlets, JSP), ASP.NET (C#), etc.These languages handle dynamic content generation and server-side processing.
• Database-Stores and manages data. Common databases include MySQL, PostgreSQL, MongoDB, SQLite, etc.
Interaction Flow:
Python provides various libraries and modules to work with different communication protocols. For
example, the requests library is commonly used for working with HTTP, while the socket module allows you
to implement communication using TCP/IP.
TO INTERACT WITH A REMOTE HTML SERVER, YOU TYPICALLY USE HTTP (HYPERTEXT TRANSFER
PROTOCOL) FOR COMMUNICATION. YOU CAN MAKE REQUESTS USING METHODS LIKE GET OR POST AND
RECEIVE RESPONSES, OFTEN IN THE FORM OF HTML, JSON, OR OTHER DATA FORMATS. JAVASCRIPT, AJAX,
AND LIBRARIES LIKE XMLHTTPREQUEST OR FETCH API ARE COMMONLY EMPLOYED FOR CLIENT-SIDE
INTERACTIONS.
FORM HANDLING
Form handling in web development involves creating HTML forms for user data input. When users
submit the form, the data is sent to the server using HTTP methods like GET or POST.
Key points:
• HTML Forms: Create forms with input elements.
• Form Submission: Use GET or POST to send data to the server.
• Server-Side Handling: Process data on the server using scripting languages.
• Validation: Validate data on both the client and server sides for security.
• AJAX (Optional): Enable asynchronous form submission for a smoother user experience.
• Security Considerations: Protect against XSS and CSRF attacks.
• File Uploads (If needed): Handle file uploads properly.
• Feedback and Confirmation: Provide user feedback after form submission.
AJAX for Remote Interaction
What is AJAX?
• Asynchronous JavaScript and XML (AJAX) is a technique for
communicating with a remote server asynchronously,
without reloading the entire page. This allows for smoother,
more dynamic user experiences.
• It's a set of web development techniques allowing web
pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes.
• AJAX is crucial for enhancing user experience by enabling
seamless, dynamic, and asynchronous updates without
requiring a full page reload.
How AJAX Works
• Trigger an event: User interacts with an element on the page (e.g., clicking a
button, submitting a form).
• Send an asynchronous request: JavaScript constructs an HTTP request and sends
it to the server without reloading the page.
• Server processes the request: The server receives the request, processes it (e.g.,
retrieves data from a database), and prepares a response.
• Receive and update the page: The server sends the response back to the
browser. JavaScript then updates the relevant parts of the webpage with the
newly received data.
Case Studies :
INTERACTING WITH REMOTE HTML SERVERS OFTEN INVOLVES MAKING HTTP REQUESTS AND
HANDLING RESPONSES. HERE ARE SOME REAL-WORLD EXAMPLES:
• Fetching Data from an API: Many web applications expose APIs that allow developers to
retrieve data. For instance, you might use the requests library in Python to make HTTP
requests to a server and receive JSON data in response. This data can be used to update
the content of a web page dynamically.
• Submitting Form Data: When interacting with web forms, you might need to submit
data to a server. This is common in scenarios like user authentication or submitting
search queries. You can use libraries like requests in Python to send POST requests with
form data.
• Web Scraping: Web scraping involves extracting information from web pages. Libraries
like BeautifulSoup and requests in Python can be used to download HTML content and
extract specific data from it. However, be sure to review the website's terms of service to
ensure compliance.
4. AJAX Requests: Modern web applications often use AJAX (Asynchronous JavaScript and
XML) to update parts of a web page without reloading the entire page.
Moreover, interacting with remote HTML servers provide us with many benefits. Some of
them are:
• Data Retrieval and Exchange: Access information from external sources through web
services and APIs.
• Real-Time Updates: Enable dynamic and responsive user interfaces without full page
reloads.
• Content Management: Dynamically update content based on user input or changing
conditions.
• User Authentication and Authorization: Securely manage access to user-specific data and
resources.
Fetch API
AJAX Requests
Conclusion Points
Efficiency Across Functions:
• Doing things online is way smoother now. Think quick searches that happen right away, forms that tell you if
you're doing it right instantly, and updates that don't bother you while you're busy. It's like the web is learning
to be more efficient in lots of cool ways.
User-Centric Web Development:
• When you're on the internet, it's all about you. The websites and tools are designed to make your experience
better, not more complicated. It's like having a personal guide through the online world, making things easier for
you.
Empowerment Through Simplicity:
• Sometimes, the tech world can sound like a complicated language. But when we talk about tools for talking to
faraway servers, it's not about confusing stuff. It's about making your online time simple and easy, so you can focus
on what you want to do.
Meeting and Exceeding Expectations:
• Web developers are like architects for the internet. They use tools like AJAX to make sure the websites and apps not
only do what you expect but also surprise you with even cooler things. It's like they're always working to make your
online world better than you thought it could be.
HTML Structure:
• <!DOCTYPE html>: Defines the document type and version of HTML used.
• <html lang="en">: Specifies the language of the document as English.
• <head>: Contains metadata such as character set, viewport settings, and the title of the
document.
• <body>: Contains the visible content of the page.
Form:
• <form id="userForm">: Creates a form with the ID attribute set to "userForm".
• <label for="usernameInput">Username:</label>: Provides a label for the username input
field.
• <input type="text" id="usernameInput" name="username">: Creates an input field for the
username. The ID is "usernameInput", and the name attribute is "username".
• <button type="button" onclick="retrieveUsername()">Retrieve Username</button>:
Creates a button triggering the retrieveUsername() function when clicked.
JavaScript:
• function retrieveUsername() { ... }: Defines the retrieveUsername function.
• var username = document.getElementById('usernameInput').value;: Retrieves the value
entered in the input field with the ID "usernameInput" and stores it in the username
variable.
• alert('Username: ' + username);: Displays an alert box showing the retrieved username.
Running Queries:
The program doesn’t use any query language like SQL; however, it utilizes JavaScript to query the
Document Object Model (DOM) of the HTML page. The key query here is
document.getElementById('usernameInput').value;, which uses getElementById to retrieve the
value entered in the input field with the ID "usernameInput".
When the button is clicked, the retrieveUsername() function is executed, accessing the value
entered in the input field and displaying it in an alert.
Queries in this context refer to selecting elements from the HTML structure using JavaScript
methods like getElementById, which retrieve elements by their unique IDs, classes, or other
attributes to perform actions or retrieve information from those elements.
FORM SUBMISSION
There are a few ways HTML can interact with data:
AJAX
HTML Templating
• Form Submission: HTML can contain forms that allow users to input data,
which can then be submitted to a server for processing. This data can be used
to query a database or perform other actions on the server.
• AJAX (Asynchronous JavaScript and XML): Using JavaScript, HTML pages can
make asynchronous requests to a server without reloading the entire page.
These requests can retrieve data (via APIs) and update the HTML content
dynamically.
• HTML queries contribute to the performance improvements associated with PWAs, providing a faster
and more responsive user experience.
• JavaScript frameworks (e.g., React, Angular, Vue) and their impact on how HTML queries are
structured and executed.
• Code splitting and lazy loading of JavaScript to improve performance, exploring how HTML queries
can be optimized for efficient loading of resources.
Python provides different modules like urllib, requests etc. To download files from the
web. We are going to use the request library of python to efficiently download files
from the URLs.
1. Import module-
● Example :-
● Output :-
Introduction to Common
Gateway Interface (CGI)
A BRIEF HISTORY !
- When a client (e.g., a web browser) sends a request to a web server for a CGI
script, the server launches the script.
- The server sets up the script's environment, including passing information
about the request through environment variables.
- The script processes the request, generates dynamic content, and sends it
back to the server.
- The server then sends the generated content as the HTTP response to the
client.
Input Handling
- CGI scripts can receive input data from the client through query parameters
(GET), form submissions (POST), or other means.
- Input data is often accessed through the cgi.FieldStorage module in
Python.
CGI Environment Variables
CGI scripts generate dynamic content, typically in HTML format, based on the
input received.
- The script prints the HTTP header followed by the content to the standard
output. The header includes the content type (Content-type) and other
metadata.
Output :
Thank you!