UNIT – IV
GUI Programming
Q. Write a Tkinter and Python Programming ? Write a process of installation of Tkinter? 10M
Python Tkinter is a standard GUI (Graphical User Interface) library for Python which provides a fast and easy way to create desktop applications. Tkinter provides a variety of widgets like buttons, labels, text boxes, menus and more that can be used to create interactive user interfaces. Tkinter supports event-driven programming, where actions are taken in response to user events like clicks or keypresses. It's cross-platform, meaning applications built with Tkinter can run on Windows, macOS, and Linux without modification.
To install Tkinter
Tkinter comes as part of standard Python installation. So if you have installed the latest version of Python, then you do not have to do anything else. You can determine whether Tkinter is available for your Python interpreter by attempting to import the Tkinter module.
Syntax:
import tkinter
Create First Tkinter GUI Application:
- Import the tkinter module.
- Create the main application window.
- Add the widgets like labels, buttons, frames, etc. to the window.
- Call the main event loop so that the actions can take place on the user's computer screen.
Tkinter Methods:
Tk()
To create a main window in Tkinter, we use the Tk() class. The syntax for creating a main window is as follows:
Syntax:
root = tk.Tk(screenName=None, baseName=None, className='Tk', useTk=1)
screenName: This parameter is used to specify the display name. This parameter can be used to set the base name of the application.
baseName: We can change the name of the window by setting this parameter to the desired name.
className: We can change the name of the window by setting this parameter to the desired name.
useTk: This parameter indicates whether to use Tk or not.
mainloop()
This method is used to start the application. The mainloop() function is an infinite loop that is used to run the application. It will wait for events to occur and process the events as long as the window is not closed.
Tkinter Example:
import tkinter as tktop = tkinter.Tk() # creating the application main windowtop.title("Welcome") # title of main windowtop.geometry("400x300") # size of main windowtop.mainloop() # calling the event main loop
Main Window (400x300)
Common Tkinter Widgets:
Here are some of the commonly used Tkinter widgets:
- Label: This is used to display simple text.
- Button: A simple button that can be clicked to perform an action.
- Entry: Simple input field to take input from the user. This is used for single-line input.
- Text: This can be used for multi-line text fields, to show text, or to read input from the user.
- Canvas: This widget can be used for drawing shapes, images, and other graphics.
- Frame: This acts as a container widget that can be used to group other widgets together.
- Checkbutton: A checkbox widget used for creating an option on or off.
- Listbox: This is used to create a list widget used to display a list of values.
- Radiobutton: This is used to create a list of options.
- Scrollbar: This widget is used for scrolling content in widgets like Text and Listbox.
Fonts, Colors, Images in Tkinter
The choice of fonts, colors, and images can make a significant impact on the user experience and the overall aesthetic appeal of an application.
- Fonts
- Colors
- Choose Color Dialog
- Images
- Loading Images in Tkinter using PIL Resize Image
- Images as Backgrounds
Tkinter Program Example:
import tkinter as tk# Create the main windowwindow = tk.Tk()window.title("My First GUI")# Create a label widgetlabel = tk.Label(window, text="Hello, Tkinter!")label.pack()# Create a button widgetbutton = tk.Button(window, text="Click Me")button.pack()# Run the main loop (to display the window and handle events)window.mainloop()
Q. Briefly descourse about Tour of Other GUIs?
Python has plenty of frameworks for developing GUIs that deliver a high-quality user experience without a hefty price tag. Here are some of the most popular Python GUI frameworks used by developers.
1. PyQt5
Riverbank Computing's PyQt5 is built around the Qt framework, which is a cross-platform framework used for creating a plethora of applications for various platforms.
The PyQt5 package includes a detailed set of bindings for Python based on the version of the Qt application framework.
Similar to the Qt5 framework, PyQt5 is also fully cross-platform and supports applications for platforms like Windows, Mac, Linux, iOS, Android and more.
Key Features:
- Compatible with Windows, Mac, Linux, iOS and Android platforms.
- Qt Designer modules support drag-and-drop features.
- Online documentation and resources are available due to PyQt5's popularity.
2. Tkinter
Often referred to as the go-to GUI toolkit by a majority of Python developers, Python contributor Fredrik Lundh created Tkinter to equip modern developers with a standard interface to the Tk GUI toolkit with its Python bindings.
In Tkinter's world, most of the visual elements that we're familiar with are called widgets and each of these widgets offers a different level of functionality.
3. Kivy
Written using a mix of Python and Cython, Kivy is an open-source GUI framework for building user interfaces encompassing multiple applications.
It implements a natural user interface (NUI), a kind of interface where the user naturally usually keeps invisible learns various interactions provided by a user interface that's intuitive.
The most common use of the Kivy GUI framework can be seen in Android applications. Other widespread implementations of the framework can be seen in the user interfaces of Linux, Windows, Raspberry Pi and macOS devices.
Key Features:
- Free and open-source, despite being under the MIT license.
- Provides built-in support for OpenGL ES 2 to create powerful graphics.
- Compatible with Linux, Windows, Raspberry Pi and macOS devices.
4. wxPython
wxPython, developed by programmer Robin Dunn, is a Python extension module that acts as a wrapper for the wxWidgets API.
wxPython allows Python developers to create native user interfaces that add zero additional overhead to the application. The cross-platform capabilities of wxPython allow deployment to platforms like Windows, macOS, Linux, and Unix-based systems with little to no modifications.
Key Features:
- Supports the development of native user interfaces.
- Designed to make the wxWidgets toolkit easier to use.
- Compatible with Windows, macOS and Linux platforms.
5. Libavg
This open-source Libavg GUI framework is great for developing user interfaces for modern touch-based devices.
On the graphics-intensive side, video decoding, visual effects and compositing are all handled by hardware acceleration achieved via OpenGL and GPU shaders to deliver smooth and graphic-rich visuals.
Libavg supports a majority of commonly used touch drivers and offers a range of features, such as camera support, text alignment, animation support and GPU effects like blur and shadows.
Key Features:
- Ideal for building touch-based devices.
- Uses OpenGL to support video decoding and other capabilities.
- Possesses features like text alignment support and GPU effects.
6. PySimpleGUI
PySimpleGUI is designed for Python newbies to get into GUI development without spending too much time getting into the intricacies of the more advanced GUI development options available.
PySimpleGUI takes four of the widely popular Python GUI frameworks Qt, Tkinter, wxPython and Remi and turns down their difficulty a few notches by implementing most of the boilerplate code.
Beginners get to pick the GUI framework of their choice, along with easy access to the various visual elements that come with it to create intuitive user interfaces without diving deep into the frameworks.
7. PyForms
PyForms is a Python software layer at its core for the widely famous Windows Forms, which allows developers to create highly interactive user interfaces.
PyForms' cross-platform capabilities make it easier to create applications for multiple platforms with little changes to the code, eliminating unnecessary slowdowns.
PyForms provides several popular graphic-centric libraries, such as PyQt and OpenGL, to help developers create user interfaces for their applications.
The PyForms library is split into three different sections that include PyForms-GUI, PyForms-Web and PyForms-Terminal.
Key Features:
- Offers popular libraries like PyQt and OpenGL for building user interfaces.
- Can be executed in web, terminal and Windows GUI.
- Ideal for quickly building prototypes and supporting application maintenance.
8. Wax
Just like wxPython was a wrapper for the wxWidgets GUI toolkit, the Wax GUI framework is a more developer-friendly wrapper of wxPython.
Like other popular frameworks, Wax is implemented as an extension module for Python. And it also supports building cross-platform applications.
The idea behind Wax is to offer simpler access to the Python elements and objects for building GUIs by removing the low-level aspects of wxPython.
Key Features:
- Serves as a user-friendly wrapper of wxPython.
- Uses native widgets, matching the speed and efficiency of wxWindows.
- Open-source for anyone to use.
Q. Explain about Web Surfing with Python?
This program will take in a search string from you and automatically search for it, collect the web pages, and serve them to you one by one in a tabbed browser. So sit back, relax, and let the program do the work for you.
Web Surfer Program Works
The web surfer program is built using Python and leverages various modules and libraries to achieve its functionality. Here's a brief overview of how it works:
- Collect the search string from the user.
- Use the Requests module to send a search query to a search engine (e.g., Google). Retrieve the results page using the Requests module.
- Parse the HTML of the results page using the Beautiful Soup library. Extract the links from the parsed HTML.
- Open each link in a new tab using the Web Browser module.
- Set a random sleep interval between page loads to simulate natural browsing behavior.
Explain about Benefits of Using the Web Surfer Program? 5M
a) Time-saving
Instead of manually searching for web pages and clicking on each result, the program automates the process, saving you time and effort.
b) Convenience
The program serves the web pages to you in a tabbed browser, allowing you to sit back and watch them like a TV.
c) Passive browsing
By automatically loading each web page in a new tab, the program creates a passive browsing experience where you can effortlessly browse through different results.
d) Research efficiency
The program is particularly useful for researchers who need to quickly scan through multiple web pages throughout the day.
Explain Step-by-Step Creating the Web Surfer Program? 10M
1. Collecting the Search String
The first step in creating the web surfer program is collecting the search string from the user.
This can be done using the sys module in Python. Here's an example of how to capture the search string:
import sys# Get the search string from the command line argumentssearch_string = ' '.join(sys.argv[1:])
2. Getting the Results Page
Once we have the search string, we need to send it to the search engine and retrieve the results page. We can achieve this using the Requests module.
import requests# Assemble the URLsearch_query = "https://www.google.com/search?q=" + search_string# Get the results pageresponse = requests.get(search_query)# Check if the page was fetched successfullyif response.status_code == requests.codes.ok:results_page = response.textelse:print("Error in fetching the web page")sys.exit(1)
3. Parsing the Results Page with Beautiful Soup
Next, we need to parse the HTML of the results page to extract the links. This can be achieved using Beautiful Soup.
from bs4 import BeautifulSoup# Create a Beautiful Soup objectsoup_page = BeautifulSoup(results_page, "html.parser")# Extract the links from the soup pagelinks = soup_page.find_all('a')for link in links:print(link.get('href'))
4. Extracting the Links from the Results Page
Once we have the links, we can extract them and store them in a list.
Example:
def get_links(soup_page):# Extract the links from the soup pagelinks = soup_page.find_all('a')# Create a list of the href attributesextracted_links = [link.get('href') for link in links]return extracted_links
5. Opening the Links in New Browser Tabs
Finally, we can open each link in a new tab using the webbrowser module.
import webbrowser# Open each link in a new browser tabfor link in extracted_links:webbrowser.open_new_tab(link)
Q. How to Create Simple Web Clients?
A web client is a software application that uses Hypertext Transfer Protocol (HTTP) to format, transmit, and receive requests, web contents, services, or resources from web servers.
It's often called a web browser, but a web client is a wider term that encompasses both web browsers and web applications.
Advanced Web Clients
Advanced web clients are more than just simple web browsers; they are applications that perform complex tasks, often involving automated interactions with the web. They can be used for tasks like web scraping, testing websites, or accessing services through web interfaces, often requiring more sophisticated functionality than a basic web browser.
Examples of Advanced Web Clients
Key Features of Advanced Web Clients
- Automation: Many advanced clients automate tasks, such as data extraction or website testing.
- Programmability: Some clients allow custom scripting or programming to enhance their functionality.
- Extensive Capabilities: They offer a wider range of features than basic web browsers, including advanced filtering, data manipulation, and reporting.
- Integration with Other Systems: They can integrate with other systems or services, enabling seamless workflow.
- Performance and Scalability: Advanced clients often prioritize performance and scalability, allowing efficient handling of large amounts of data or complex tasks.
Q. Explain Advanced Web Clients
Advanced web clients are web-based applications or software that go beyond basic web browsing functionality. They often involve complex interactions with web servers, use modern frameworks, and can be designed to handle various tasks like web indexing, offline browsing, or accessing services through web service clients.
Advanced Web Technology:
Advanced web technology refers to the use of modern tools, frameworks, and techniques to create dynamic, efficient, and interactive web applications. This includes technologies like HTML5, CSS3, JavaScript frameworks, and APIs.
1. Beyond Basic Browsing
Standard web browsers are basic clients that primarily handle viewing and downloading web pages. Advanced clients perform more complex operations, such as crawling and indexing the web.
Examples include programs that download entire websites for offline viewing, bots used for scraping data, or web service clients that interact with web services.
2. Modern Frameworks and Technologies
Advanced web development often utilizes frameworks like React, Angular, and Vue.js to create complex and interactive applications.
These frameworks provide tools for building reusable components, managing application state, and handling client-side logic.
Advanced techniques like AJAX (Asynchronous JavaScript and XML) and the Document Object Model (DOM) are used to dynamically update web pages without requiring full page reloads.
3. Examples of Advanced Clients
Q. Explain about Essential Skills for Advanced Web Developers? 4M
CGI
Q. Explain about CGI – Helping Servers Process Client Data ?
CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between a server application and the client application (or the browser).
The programs based on CGI communicate between the web servers and the client. Whenever the client makes a request, it sends it to the web server, and the CGI programs return output to the web server based on the input that the client-server provides.
Common Gateway Interface (CGI) provides a standard method for gateway programs to interface with data servers like an HTTP server.
The programming with CGI is written dynamically, which generates web pages responding to the input from the user of the web pages and interacts with the software on the server.
Common Gateway Interface:
The following common gateway diagram helps to understand how CGI works when a user clicks a hyperlink to browse any web page. A web browser operating on a client machine uses HyperText Transfer Protocol (HTTP) to exchange information with a web server.
The CGI program resides on the same system where the web server is present and operates from the same system. Based on the request type received from the browser, the web server attempts to either provide the document from its document file system or run a CGI program.
Steps in CGI Processing
- A user requests the HTTP web server and demands the URL.
-
The user can also type the URL in a browser's location window, which can be a hyperlink or specified as an HTML
<form>tag. - The web server analyzes the URL and looks for the filename. Otherwise, it activates the gateway program mentioned in the URL and sends parameters to the program via the URL.
- The Common Gateway Interface gateway processes the required information and sends file/HTML text to the web server.
- Additionally, the server appends the MIME header and sends the HTML text to the browser.
- Taking the result from a web server, the web browser displays either the received document or an error message.
Q. Explain Applications of Common Gateway Interface?
CGI transforms the Web from collecting static data into a new interactive structure, wherein users can interact with the web applications.
Some applications designed using CGI are:
a) Forms
Forms are one of the most significant users of CGI. Forms allow the user to share information and are a subset of HTML. A CGI program makes these forms interactive for both user and provider by processing and selecting the appropriate fields to match the selection criteria.
b) Gateway
Web gateways are programs or scripts used to access necessary information that is not directly readable by the client database. The CGI program is employed to serve as a gateway and use an appropriate programming language to read the information, format it, and share it with the client.
c) Virtual Documents
Virtual documents are an important part of CGI. While virtual documents are created as per the user's request, they can vary from virtual HTML pages, images, plain text, to sometimes audio.
Features of CGI:
- CGI is utilized to create simple shell scripts and interactive applications.
- They are well defined with a set of rules.
- CGI is a technology that easily interfaces with HTML, Perl, C.
- CGI is highly compatible with existing browsers.
Advantages of Python CGI Programming:
- They are portable and can work on many operating systems and web servers.
- They are independent of the language of the script.
- The programs are scalable in nature and can perform both simple and complex tasks.
- They develop dynamic communication in web applications.
- They decrease development and maintenance costs.
Q. Explain Building CGI Application step by step ?
Steps Involved in Creating a CGI Script:
Here are the steps involved in creating a basic Common Gateway Interface script:
1. Choose a Programming Language
Decide which programming language you will use for your CGI script. Standard options include:
- Perl
- Python
- PHP
2. Set Up Your Environment
Make sure your web server (Apache, Nginx, etc.) has been configured properly for handling CGI scripts. Usually, this involves enabling CGI within the server configuration file and setting up the appropriate directory.
3. Write the Script
Use some text editor to create a new file for your script. Typically, the extension reflects the language used (.pl for Perl, .py for Python).
Write script code that handles requests and generates responses. Ensure it starts with the correct shebang line for the language chosen.
4. Set Permissions
Change permissions of the file in such a way that allows execution of the script; normally done through the command line using chmod.
5. Place the Script on the Server
Move the script to the server's CGI directory. This directory is typically set up to handle executable files.
6. Test the Script
Open a web browser and navigate to the script's URL. Thereafter, check the output to ensure the script executes correctly and generates the expected response.
7. Debug and Refine
If the script doesn't work as expected, review server logs or error messages to troubleshoot issues. Edit the script based on feedback or errors and retest to ensure it performs as intended.
8. Security and Maintenance
Ensure the script is secure, mainly if it handles sensitive data. Therefore, implement proper validation and sanitation of inputs.
Regularly update and maintain the script to address any new issues or requirements.
Q. Explain about HTTP Headers Used in CGI Programming?
There are a few additional essential HTTP headers that you will regularly utilize when developing CGI programs.
In CGI programming, HTTP headers provide additional information about the response to the client web browser.
Some of the essential HTTP headers commonly used in CGI programming include:
1. Content-Type
This header specifies the media type of the response body, such as text/html for HTML content or application/json for JSON data.
2. Content-Length
This header specifies the size of the response body in bytes. This is important for the client browser to know how much data to expect and when the response is complete.
3. Location
This header redirects the client to a different URL. It is commonly used in conjunction with 3xx status codes, such as 301 (Moved Permanently) or 302 (Found).
4. Set-Cookie
This header sets cookies on the client browser. Cookies are stored on the client's computer and are small pieces of data. They are sent back to the server with each subsequent request. They store user preferences, session information, or other data.
5. Cache-Control
This header controls how the client or intermediate proxies cache the response. It can be used to specify that the response should not be cached or that it should only be cached for a certain amount of time.
Q. Write a CGI GET and POST Methods?
We must have encountered many situations where we need to pass some information from our browser to a web server and finally to our CGI program.
The browser most often uses two methods to pass this information to the web server:
- GET method
- POST method
GET Method:
Example:
http://www.testing.com/cgi-bin/hellouser.py?key1=value1&key2=value2
The GET method is the default method for passing information from a browser to a web server and produces a long string that appears in your browser's Location box.
Never use the GET method if you have a password or other sensitive information to pass to the server.
The GET method has a size limit: only 1024 characters can be sent in the request string.
The GET method sends information using the QUERY_STRING header and will be accessible in your CGI program via the QUERY_STRING environment variable.
You can pass information by simply concatenating key-value pairs along with any URL, or you can use HTML <FORM> tags to pass information using the GET method.
Q. Explain CGI Environment Variables using Python?
In CGI programming, environment variables store information about the request and the server environment. The CGI program can access these variables and generate a dynamic response.
You can access the CGI environment variables using the os module.
This module provides an environment dictionary that contains the current environment variables.
For example, you can access the REQUEST_METHOD variable, which specifies the HTTP method of the request.
import osprint(os.environ)
Some common CGI environment variables include:
- QUERY_STRING: The query string of the URL, if any.
- CONTENT_TYPE: If provided, the media type of the request body.
- CONTENT_LENGTH: The size of the request body in bytes, if provided.
- HTTP_COOKIE: The cookies sent by the client with the request.
- REMOTE_ADDR: The IP address of the client computer that makes the request.
Q. Write Advanced CGI?
Advanced CGI programming in Python involves techniques that go beyond basic form handling and output generation. These techniques include using cookies, handling multiple values for the same form field, and managing file uploads.
Cookies
Cookies enable personalized browsing. With cookies we can store information about a client.
For example, about previous selections made, in passing data from one script to another. We can store personal information such as identification and passwords; or information from previous visits to the site.
Potential applications include:
- Customizing displayed content
- Storing encrypted passwords for fast access
- Personalized pricing
Cookies are data stored by the web server on the client computer, managed by the browser.
Cookies Example
The session below illustrates the use of the cookies module.
from http import cookiesc = cookies.SimpleCookie()c['data'] = 'Fri 8 Apr 2016'print(c)
Output:
Set-Cookie: data="Fri 8 Apr 2016"
Password Encryption
We can use cookies for login names and passwords. For security purposes, we store only the encrypted passwords.
A secure hash algorithm is often called a one-way function. It is computationally infeasible to compute its inverse. As a hash function, the collision rate is low, which means that there is a very low chance that two different messages generate the same key.
The server encrypts the password before sending it to the client. The authentication happens by comparing encrypted passwords.
A session with the hashlib module is illustrated below:
from hashlib import sha1m = sha1()m.update('this is me'.encode())print(m)print(m.hexdigest())
Example hash output:
99cf08dcdc3ae19fae7ec8b531797786611406
Authentication via Email
We can restrict access to our web application via a third-party email authentication. For example, we may grant access only to those with a valid UIC email account.
Q. Explain about SMTP? 4M
The Simple Mail Transfer Protocol (SMTP) is an internet standard for email transmission.
In Python we can send email using smtplib.
For example, to connect to the Gmail email server:
from smtplib import SMTPSMTP('smtp.gmail.com', 587)s.starttls()
Response:
(220, b'2.0.0 Ready to start TLS')
Q. Explain about File Upload and File Download? 10M IMP
File Uploads:
File uploads are handled using the multipart/form-data encoding. The cgi.FieldStorage object treats uploaded files as file-like objects, which can be read and processed.
To upload a file, the HTML form must have the enctype attribute set to multipart/form-data.
The input tag with the file type will create a Browse button.
Example
<html><body><form enctype="multipart/form-data" action="save_file.py" method="post"><p>File: <input type="file" name="filename"></p><p><input type="submit" value="Upload"></p></form></body></html>
File Download Dialog Box:
Sometimes, it is desired that you want to give an option where a user will click a link and it will pop up a "File Download" dialogue box to the user instead of displaying actual content.
This is very easy and can be achieved through an HTTP header.
For example, if you want to make a FileName file downloadable from a given link, then its syntax will be as follows:
#!/usr/bin/python# HTTP Headerprint 'Content-Type:application/octet-stream; name="FileName"\r\n'print 'Content-Disposition: attachment; filename="FileName"\r\n\r\n'# Actual File Content will go herefo = open("foo.txt", "rb")str = fo.read()print str# Close opened filefo.close()
Q. Explain about Web (HTTP) Servers? 10M IMP
A web server is actually a network application, running on some machine and listening on some port.
A web server is a computer where web contents are stored.
A web server serves web pages to clients across the Internet or an intranet.
It hosts the pages, scripts, programs and multimedia files and serves them using HTTP, a protocol designed to send files to web browsers.
Common examples of web servers:
- Apache Web Server
- IIS Web Server
- Nginx Web Server
- LightSpeed Web Server
Types of Web Servers:
There are two types of web servers:
Dedicated Web Servers
In this, one web server is dedicated to a single user. This is suitable for websites with more web traffic.
Shared Web Servers
In this, a web server is assigned to many clients and is shared among all the clients.
Web Server Works: 4M
For example, a user wants to see a website like www.google.com. The user types the URL using a client program (web browser), but before this they need to be physically connected to the computer of the user and the web server. That is the job of the Internet.
Using the TCP/IP suite of protocols, it establishes the connection using a combination of wired and wireless media.
When the connection is established, the client sends a request called an HTTP message. Because HTTP is a connectionless protocol, the client disconnects from the server while waiting for the response.
The server on the other side receives the request, prepares the response, establishes the connection again and sends the response.
Again, an HTTP message is sent to the client. When the two computers completely disconnect, the process is complete.
HTTP Protocol: 4M
HTTP stands for HyperText Transfer Protocol.
It is an application-layer protocol that allows web-based applications to communicate and exchange data.
HTTP is the messenger of the web.
The computers that communicate via HTTP must speak the HTTP protocol. It is a TCP/IP-based protocol.
It is used to deliver contents, for example:
- Images
- Audio
- Videos
- Documents
- Web pages
Using HTTP is the most convenient way to quickly and reliably move data on the web.
Q. Write Features of the http.server Module? 10M IMP
1. Basic HTTP Functionality
The http.server module supports standard HTTP methods such as GET and HEAD, allowing developers to handle simple requests.
2. Easy Setup
Creating an HTTP server using the http.server module requires minimal code. You can easily set up a functional server with just a few lines of code.
3. Static File Serving
The module can serve static files, making it helpful in hosting simple websites or web applications that rely on static content.
4. Portability
Python is a cross-platform language, and the HTTP server code written using the http.server module will work consistently across different operating systems.
No comments:
Post a Comment