0% found this document useful (0 votes)
7 views55 pages

20934254 Python Module 3

The document discusses the evolution of graphics processing in computing, focusing on Turtle graphics in Python, which allows users to create drawings using a virtual turtle that moves based on commands. It also covers image processing principles, including sampling, digitizing images, and various image file formats like JPEG and GIF, along with manipulation techniques such as converting images to grayscale and blurring. Additionally, it introduces the images module in Python for image handling and basic operations for image manipulation.

Uploaded by

jocktmpx4oxc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views55 pages

20934254 Python Module 3

The document discusses the evolution of graphics processing in computing, focusing on Turtle graphics in Python, which allows users to create drawings using a virtual turtle that moves based on commands. It also covers image processing principles, including sampling, digitizing images, and various image file formats like JPEG and GIF, along with manipulation techniques such as converting images to grayscale and blurring. Additionally, it introduces the images module in Python for image handling and basic operations for image manipulation.

Uploaded by

jocktmpx4oxc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

24-04-23

Monday

MODULE III – Graphics

* Until about 35 years ago, computers processed numbers and text almost
exclusively. Since then, the computational processing of images, video,
and sound has become increasingly important.

Simple Graphics

* Graphics is the discipline that underlies the representation and display of


geometric shapes in two- and three-dimensional space, as well as image
processing.

* Turtle is a Python language library that is similar to the virtual canvas


through which we can design pictures and attractive shapes.

* A Turtle graphics toolkit provides a simple and enjoyable way to draw


pictures in a window and gives you an opportunity to run several methods
with an object.

* Turtle graphics were originally developed as part of the children’s


programming language Logo

- The name is intended to suggest a way to think about the drawing


process. Imagine a turtle crawling on a piece of paper with a pen tied to its
tail.

- Commands direct the turtle as it moves across the paper and tell it to lift
or lower its tail, turn some number of degrees left or right, and
move a specified distance.

- Whenever the tail is down, the pen drags along the paper, leaving a trail.
In this manner, it is possible to program the turtle to draw pictures ranging
from the simple to the complex.

* In the context of a computer, the sheet of paper is a window on a


display screen, and the turtle is an icon, such as an arrowhead.
- At any given moment in time, the turtle is located at a specific position in
the window. This position is specified with (x, y) coordinates.

-The coordinate system for Turtle graphics is the standard Cartesian


system, with the origin (0, 0) at the center of a window. The turtle’s
initial position is the origin which is also called the home.

* The turtle has three attributes:


1. Location
2. Orientation (or direction), and
3. Pen.

* The pen, too, has attributes: color, width, and on/off state (also called
down and up).

* Together, these attributes make up a turtle’s state . The turtle’s state


determines how the turtle will behave when any operations are applied to
it.

- For example, a turtle will draw when it is moved, if its pen is currently
down, but it will simply move without drawing when its pen is currently
up.
- Operations also change a turtle’s state. For instance, moving a turtle
changes its position, but not its direction, pen width, or pen color.

* Two other important classes used in Python’s Turtle graphics system are
Screen , which represents a turtle’s associated window, and Canvas,
which represents the area in which a turtle can move and draw lines.

Turtle Operations

* Because a turtle is an object, its operations are also defined as methods.


Object Instantiation and the turtle Module

* The Turtle class is defined in the turtle module


* The following code imports the Turtle class for use in a session:

>>> from turtle import Turtle

* The next code segment creates and returns a Turtle object and opens a
drawing window.

>>> t = Turtle()

* As you can see, the turtle’s icon is located at the home position (0, 0) in
the center of the window, facing east and ready to draw.

Drawing Two-Dimensional Shapes

* Illustration 1 : Draw a square


* With loop

* Illustration 2: Draw a hexagon

* Illustration 3: Draw a radial pattern with 10 hexagons


25-04-23
Tuesday

Manipulating a Turtle’s Screen

As mentioned earlier, a Turtle object is associated with instances of the


classes Screen and Canvas , which represent the turtle’s window and the
drawing area underneath it.

The Screen object’s attributes include its width and height in pixels, and its
background color, among other things.

You access a turtle’s Screen object using the notation t.screen , and then
call a Screen method on this object.

The methods window_width() and window_height() can be used to locate


the boundaries of a turtle’s window.

The following code resets the screen’s background color, which is white by
default, to orange, and prints the coordinates of the upper left and lower
right corners of the window:

from turtle import Turtle


t = Turtle()
t.screen.bgcolor("orange")
x = t.screen.window_width() // 2
y = t.screen.window_height() // 2
print((-x, y), (x, -y))

Colors and the RGB System

* The rectangular display area on a computer screen is made up of colored


dots called picture elements or pixels. The size of a pixel is determined by
the size and resolution of the display.

- The smaller the pixel, the smoother the lines drawn with them will be.

* Each pixel represents a color. The turtle’s default color is black


- You can easily change it to one of several other basic colors, such as
red, yellow, or orange, by running the pencolor method with the
corresponding string as an argument.

- Among the various schemes for representing colors, the RGB system is a
common one. The letters stand for the color components of red, green, and
blue, to which the human retina is sensitive.

* The colour components are mixed together to form a unique color value.
Each color component can range from 0 through 255. The value 255
represents the maximum saturation of a given color component, whereas
the value 0 represents the total absence of that component

256 * 256 * 256, or 16,777,216 distinct color values are possible

* The Turtle class includes the pencolor and fillcolor methods for
changing the turtle’s drawing and fill colors, respectively. These methods
can accept integers for the three RGB components as arguments.
* fillcolor(col): This helps to choose the color for filling the shape. It takes
the input parameter as the color name or hex value of the color and fills the
upcoming closed geographical objects with the chosen color. Color names
are basic color names i.e. red, blue, green, orange.

begin_fill(): This function tells turtle that all upcoming closed graphical
objects needed to be filled by the chosen color.
end_fill(): this function tells turtle to stop the filling upcoming closed
graphical objects.

* Illustration 1 :

# draw color-filled square in turtle

import turtle

# creating turtle pen


t = turtle.Turtle()

# taking input for the side of the square


s = int(input("Enter the length of the side of the square: "))

# taking the input for the color


col = input("Enter the color name or hex value of color(# RRGGBB): ")

# set the fillcolor


t.fillcolor(col)

# start the filling color


t.begin_fill()

# drawing the square of side s


for _ in range(4):
t.forward(s)
t.right(90)
# ending the filling of the color
t.end_fill()

* Illustration 2

# draw color filled star in turtle

import turtle

# creating turtle pen


t = turtle.Turtle()

# taking input for the side of the star


s = int(input("Enter the length of the side of the star: "))

# taking the input for the color


col = input("Enter the color name or hex value of color(# RRGGBB): ")

# set the fillcolor


t.fillcolor(col)

# start the filling color


t.begin_fill()

# drawing the star of side s


for _ in range(5):
t.forward(s)
t.right(144)

# ending the filling of color


t.end_fill()

Image Processing

* Digital image processing includes the principles and techniques for the
following:
-The capture of images with devices such as flatbed scanners and digital
cameras
- The representation and storage of images in efficient file formats
- Constructing the algorithms in image-manipulation programs such as
Adobe Photoshop

* Computers must use digital information consisting of discrete values,


whereas the the information contained in images, sound, and much of the
rest of the physical world is analog.

- Analog information contains a continuous range of values.

- Early recording and playback devices for images and sound were all
analog devices.

* The continuous analog information in a real visual scene must be


mapped into a set of discrete values. This conversion process also involves
sampling.

Sampling and Digitizing Images

* Sampling devices measure discrete color values at distinct points on a


two-dimensional grid . These values are pixels. In theory, the more
pixels that are sampled, the more continuous and realistic the resulting
image will appear.

Image File Formats

* Once an image has been sampled, it can be stored in one of many file
formats.

* A raw image file saves all of the sampled information. Here the cost is
that the file size of the image can be quite large. But the benefit is that
the display of a raw image will be the most true to life.

* Two of the most popular image file formats are JPEG (Joint Photo-
graphic Experts Group) and GIF (Graphic Interchange Format).
* Various data-compression schemes are used to reduce the file size of a
JPEG image.

- Lossless compression: This scheme examines the colors of each pixel’s


neighbors in the grid. If any color values are the same, their positions
rather than their values are stored, thus potentially saving many bits
of storage. Before the image is displayed, the original color values are
restored during the process of decompression.

- Lossy scheme: To save even more bits, another scheme analyzes larger
regions of pixels and saves a color value that the pixels’ colors
approximate. Here some of the original color information is lost. However,
when the image is decompressed and displayed, the human eye usually is
not able to detect the difference between the new colors and the original
ones.

* A GIF image relies on an entirely different compression scheme.

- The compression algorithm consists of two phases.

In the first phase, the algorithm analyzes the color samples to build a table
called color palette, of up to 256 of the most prevalent colors.

-The algorithm then visits each sample in the grid and replaces it with the
key of the closest color in the color palette.

The resulting image file thus consists of at most 256 color values and the
integer keys of the image’s colors in the palette.

This strategy can potentially save a huge number of bits of storage.

- The decompression algorithm uses the keys and the color palette to
restore the grid of pixels for display.

Image-Manipulation Operations

* Image-manipulation programs either transform the information in the


pixels or alter the arrangement of the pixels in the image.
* Operations possible are:

1. Rotate an image
2. Convert an image from color to grayscale
3. Apply color filtering to an image
4. Highlight a particular area in an image
5. Blur all or part of an image
6. Sharpen all or part of an image
7. Control the brightness of an image
8. Perform edge detection on an image
9. Enlarge or reduce an image’s size
10. Apply color inversion to an image
11. Morph an image into another image
The Properties of Images

* An image consists of a width, a height, and a set of color values


accessible by means of (x, y) coordinates

* When an image is loaded into a program such as a Web browser, the


software maps the bits from the image file into a rectangular area of
colored pixels for display.

- The coordinates of the pixels in this two-dimensional grid (ie screen


coordinate system) range from (0, 0) at the upper-left corner of an image
to (width – 1, height – 1) at the lower-right corner, where width and
height are the image’s dimensions in pixels.

* The RGB color system is a common way of representing the colors in


images. A color value consists of the tuple (r, g, b), where the variables
refer to the integer values of its red, green, and blue components,
respectively.

The images Module

* images is a small module of high-level Python resources for image


processing.

- It allows the programmer to load an image from a file, view the image
in a window, examine and manipulate an image’s RGB values, and save
the image to a file.

- The images module is a non-standard, open-source Python module


developed to support easy image processing.

* The images module includes a class named Image . The Image class
represents an image as a two-dimensional grid of RGB values.

* The images module accepts only image files in GIF for mat.
* Basic Operations on images

I. a. Imports the Image class from the images module


b. Instantiates this class using the file named smokey.gif
c. Draws the image

from images import Image


image = Image("smokey.gif")
image.draw()

Output:
* Python raises an exception if it cannot locate the file in the current
directory, or if the file is not a GIF file.

II. Once an image has been created, you can examine its width and height,
as follows:
>>> image.getWidth()
198
>>> image.getHeight()
149

III. You can print the image’s string representation

>>> print(image)
Filename: smokey.gif
Width: 198
Height: 149

IV. The method getPixel returns a tuple of the RGB values at the given
coordinates.

To get the information for the pixel at position (0, 0), which is at the
image’s upper-left corner.

>>> image.getPixel(0, 0)
(194, 221, 114)

V. Creating a new, blank image

- Instead of loading an existing image from a file, the programmer can


create a new, blank image.

- The programmer specifies the image’s width and height; the resulting
image consists of transparent pixels.
- Such images are useful for creating backgrounds for drawing simple
shapes, or for creating new images that receive information from existing
images.

- The programmer can use the method setPixel to replace an RGB value at
a given position in an image.

- Problem:

1.Create a new 150-by-150 image


2. The pixels along the three horizontal lines at the middle of the image are
then replaced with new blue pixels

Output:
3. You can save an image under its current filename or a different
filename.

>>> image.save("horizontal.gif")

VI. Loop Pattern for Traversing a Grid and to perform operations on it

Illustration: Fill a blank image in red


05/06/23
Monday

Some simple image-processing algorithms

1. Converting an Image to Black and White

* convert a color image to black and white

- For each pixel, the algorithm computes the average of the red, green, and
blue values.

-The algorithm then resets the pixel’s color values to 0 (black) if the
average is closer to 0, or to 255 (white) if the average is closer to 255.
Output:
2. Converting an Image to Grayscale

* Black-and-white photographs also contain various shades of gray known


as grayscale.

- Grayscale can be an economical color scheme, wherein the only color


values might be 8, 16, or 256 shades of gray (including black and white at
the extremes).

* Convert a color image to grayscale

- The method of replacing the color values of each pixel with their average
does not reflect the manner in which the different color components affect
human perception.

- The human eye is actually more sensitive to green and red than it is to
blue. As a result, the blue component appears darker than the other
two components.

- Therefore, to obtain the new RGB values, instead of adding up


the color values and dividing by 3, you should multiply each one by a
weight factor and add the results.

-The relative luminance proportions of green, red, and blue are .587, .299,
and .114, respectively
3. Copying an Image

* The Image class includes a clone method for this purpose.

- The method clone builds and returns a new image with the same
attributes as the original one, but with an empty string as the filename.
- The two images are thus structurally equivalent but not identical

ie, changes to the pixels in one image will have no impact on the pixels in
the same positions in the other image.
4. Blurring an Image

* edge in an image are the lines that represent a transition from one group
of similar pixels in the image to another different group.
One example of an edge is the pixels that represent the boundaries of
an object in an image, where the background of the image ends and the
object begins.

- blurring an image means, we make the colour transition from one side of
an edge in the image to another smooth rather than sudden.

- The effect is to average out rapid changes in pixel intensity.

- Blurring makes these areas appear softer, but at the cost of losing some
definition.

* The blurring algorithm resets each pixel’s color to the average of the
colors of the four pixels that surround it.
At #1, the nested auxiliary function tripleSum is defined. This function
expects two tuples of integers as arguments and returns a single tuple
containing the sums of the values at each position.

At #2, five tuples of RGB values are wrapped in a list and passed with the
tripleSum function to the reduce function. This function repeatedly applies
tripleSum to compute the sums of the tuples, until a single tuple containing
the sums is returned.

At #3, a lambda function is mapped onto the tuple of sums, and the result
is converted to a tuple. The lambda function divides each sum by 5. Thus,
you are left with a tuple of the average RGB values.
5. Edge Detection

* Edge detection removes the full colors on a color image to uncover the
outlines of the objects represented in the image.

- When artists paint pictures, they often sketch an outline of the subject in
pencil or char coal. They then fill in and color over the outline to complete
the painting. Edge detection performs the inverse function on a color
image.

* A simple edge-detection algorithm examines the neighbors below and


to the left of each pixel in an image.

- If the luminance of the pixel differs from that of either of these two
neighbors by a significant amount, you have detected an edge, and you set
that pixel’s color to black.

- Otherwise, you set the pixel’s color to white.


* Output
6. Reducing the Image Size

* The size and the quality of an image on a display medium, such as a


computer monitor or a printed page, depend on two factors: the image’s
width and height in pixels and the display medium’s resolution .

*Resolution is measured in pixels, or dots per inch (DPI).

- When the resolution of a monitor is increased, the images appear smaller,


but their quality increases.

-Conversely, when the resolution is decreased, images become larger, but


their quality degrades.

* How to reduce the size of an image once it has been captured?

- Assumption: the size of an image is its width and height in pixels

- if the height and width of an image are each reduced by a factor of N, the
number of color values in the resulting image is reduced by a factor of N2 .

* A size reduction usually preserves an image’s aspect ratio (that is, the
ratio of its width to its height).

- A simple way to shrink an image is to create a new image whose width


and height are a constant fraction of the original image’s width and height.

- The algorithm then copies the color values of just some of the original
image’s pixels to the new image

For example, to reduce the size of an image by a factor of 2, you could


copy the color values from every other row and every other column of the
original image to the new image.

- The function expects the original image and a positive integer shrinkage
factor as parameters.
A shrinkage factor of 2 tells Python to shrink the image to half of its
original dimensions, a factor of 3 tells Python to shrink theimage to one-
third of its original dimensions, and so forth.
* The loop traversesthe larger image (the original) and skips positions by
incrementing its coordinates by the shrinkage factor. The new image’s
coordinates are incremented by 1, as usual.
Graphical User Interfaces

* Most often users judge a software product by its user interface.

* 99% of the world’s computer users use interactive computer software


that employs a Graphical User Interface or GUI

* A GUI displays all information, including text, graphically to its users


and allows them to manipulate this information directly with a pointing
device.

- A GUI displays text as well as small images (called icons) that represent
objects such as folders, files of different types, command buttons,
and drop-down menus.

- In addition to entering text at the keyboard, the user of a GUI can


select some of these icons with a pointing device, such as a mouse, and
move them around on the display.

- Commands can be activated


by pressing the enter key or control keys,
by pressing a command button,
by selecting a drop-down menu item, or
by double-clicking on some icons with the mouse

The Behavior of Terminal-Based Programs and GUI-Based Programs

* A GUI program is event driven, meaning that it is inactive until the user
clicks a button or selects a menu option.

- a GUI program allows users to enter inputs in any order and waiting for
them to press a command button or select a menu option.

* In contrast, a terminal-based program maintains constant control over


the interactions with the user.

-A terminal-based program prompts users to enter successive inputs.


* Illustration of terminal-based program & its GUI version using a
program that computes and displays a person’s income tax, given two
inputs—the gross income and the number of dependents.

The Terminal-Based Version

* The terminal-based version of the program prompts the user for his gross
income and number of dependents.

- After he enters his inputs, the program responds by computing and


displaying his income tax.

- The program then terminates execution

* The user is constrained to reply to a definite sequence of prompts for


inputs. Once an input is entered, there is no way to back up and change it.

* To obtain results for a different set of input data, the user must run the
program again. At that point, all of the inputs must be re-entered.
The GUI-Based Version

* The GUI-based version of the program displays a window that contains


various components, also called widgets

* The window in Figure contains the following components:

1. A title bar at the top of the window. This bar contains the title of the
program, “Tax Calculator.”

- It also contains three colored disks. Each disk is a command button .

The user can use the mouse to click the left disk to quit the program, the
middle disk to minimize the window, or the right disk to zoom the
window.

- The user can also move the window around the screen by holding the left
mouse button on the title bar and dragging the mouse.

2. A set of labels along the left side of the window. These are text
elements that describe the inputs and outputs. For example, “Gross
income” is one label.

3. A set of entry fields along the right side of the window. These are
boxes within which the program can output text or receive it as input from
the user.
At program start-up, the fields contain default values

4. A single command button labeled Compute.


- When the user uses the mouse to press this button, the program
responds by using the data in the two input fields to compute the income
tax.

- This result is then displayed in the output field.

5. The user can also alter the size of the window by holding the mouse on
its lower-right corner and dragging in any direction.

* Advantages of using GUI

- The user is not constrained to enter inputs in a particular order.


Before she presses the Compute button, she can edit any of the data in
the two input fields.
- Running different data sets does not require re-entering all of the data.
The user can edit just one value and press the Compute button to observe
different results.

* The improvement of GUI over Terminal based program is even more


noticeable as the number of command options increases and the
information to be presented grows in quantity and complexity.
Event-Driven Programming

* In computer programming, event-driven programming is a


programming paradigm in which the flow of the program is determined by
events of user actions (mouse clicks, key presses etc)

- A GUI-based program opens a window and waits for the user to


manipulate window components with the mouse.

-These user-generated events, such as mouse clicks, trigger operations in


the program to respond by pulling in inputs, processing them, and
displaying results.

- This type of software system is known as event-driven, and the type of


programming used to create it is called event-driven programming .

Coding an event driven program consists of many steps

1. Define a new class to represent the main application window.

2. Instantiate the classes of window components needed for this


application, such as labels, fields, and command buttons.

3. Position these components in the window.

4. Register a method with each window component in which an event


relevant to the application might occur.

5. Define these methods to handle the events.

6. Define a main function that instantiates the window class and runs the
appropriate method to launch the GUI.

* In the GUI version of the tax calculator program consists of the window
and its components, including the labeled entry fields and the Compute
button.
- The action triggered when Compute button is clicked, is a method call.
This method fetches the input values from the input fields and performs
the computation.

- The result is then sent to the output field to be displayed.

Coding Simple GUI-Based Programs

* Python’s standard tkinter module includes classes for windows and


numerous types of window components.

- Since tkinter module’s use can be challenging for beginners, a custom,


open-source module called breezypythongui is used here.

* You can find the code, documentation, and installation instruc-


tions for the breezypythongui module at

http://home.wlu.edu/~lambertk/breezypythongui/.

Illustration 1: A Simple “Hello World” Program

* It defines a class for a main window that displays a greeting.


* Output:

* A new window class extends the EasyFrame class

- “extends,” mean “repurposes” or “provides extra functionality for.”

- The EasyFrame class provides the basic functionality for any window.

* The class, named LabelDemo , provides additional functionality to the


EasyFrame class

1. Import the EasyFrame class from the breezypythongui module.


This class is a sub class of tkinter ’s Frame class, which represents a
top-level window. In many GUI programs, this is the only import that you
will need.

2. Define the LabelDemo class as a subclass of EasyFrame .

The LabelDemo class describes the window’s layout and functionality


for this application.

3. Define an __init__ method in the LabelDemo class. This method is


automatically run when the window is created.

- The __init__ method runs a method with the same name on the
EasyFrame class and then sets up any window components to display in
the window.
- In this case, the addLabel method is run on the window itself.

The addLabel method creates a window component, a label object with


the text “Hello world!,” and adds it to the window at the grid posi tion (0,
0).

4. The last five lines of code define a main function and check to see if the
Python code file is being run as a program.

- If this is true, the main function is called to create an instance of the


LabelDemo class.
- The mainloop method is then run on this object.

-At this point, the window pops up for viewing.

Note that mainloop , as the name implies, enters a loop. The Python
Virtual Machine runs this loop behind the scenes. Its purpose is to wait for
user events, as mentioned earlier. The loop terminates when the user clicks
the window’s close box.

06/06/23
Tuesday
A Template for All GUI Programs

* The structure of a GUI program is always the same, no matter how


complex the application becomes. Here is the template for this structure:
* A GUI application window is always represented as a class that extends
EasyFrame .

*The __init__ method initializes the window by setting its attributes and
populating it with the appropriate GUI components.

* The last lines of code, beginning with the definition of the main function,
create an instance of the application window class and run the mainloop
method on this instance.

- The window then pops up and waits for user events. Pressing the
window’s close button will quit the program normally.

* The event handling methods provide the responses of the application to


user events.

Subclassing and Inheritance as Abstraction Mechanisms


* The first example program defined a new class named LabelDemo . This
class was defined as a subclass of the class breezypythongui.EasyFrame ,
which in turn is a subclass of the class tkinter.Frame .

* When you make a new class a subclass of another class, your new class
inherits and thereby acquires the attributes and behavior defined by its
parent class, and any of its ances tor classes, for free.

* the LabelDemo class customizes the EasyFrame method __init__ to set


up a window with a specific window component.

Windows and Window Components

* A window has several attributes. The most important ones are its
- title (an empty string by default)
- width and height in pixels
- resizability (true by default)
- background color (white by default)

* We can override the window’s default attributes in the foloowing three


ways:
1. You can change the title, by supplying another string as an optional title
argument to the EasyFram method __init__ .

- Along with that you can provide a custom initial width and height in
pixels.

Note that whenever we supply arguments to a method call, we use the


corresponding keywords for clarity in the code.

2. Another way to change a window’s attributes is to reset them in the


window’s attribute dictionary .

- Each window or window component maintains a dictionary of its


attributes and their values.

- To access or modify an attribute, the programmer uses the standard


subscript notation with the attribute name as a dictionary key.

- The window’s background color can be set to yellow with the following
statement:

self["background"] = "yellow"

3. The final way to change a window’s attributes is to run a method


included in the EasyFrame class.
* For example, the window’s size can be permanently frozen with the
following statement:

self.setResizable(False)

Window Layout

* Window components are laid out in the window’s two-dimensional grid .

- The grid’s row and columns are numbered from the position (0, 0) in the
upper left corner of the window.

- A window component’s row and column position in the grid is specified


when the component is added to the window.

Illustration: Program (layoutdemo.py) that labels the four quadrants of the


window.
* Labels usually appear to the left of data entry fields and their default
alignment is northwest.

- The programmer can override the default alignment by including the


sticky attribute as a keyword argument when the label is added to the
window.

- The values of sticky are the strings “N,” “S,” “E,” and “W,” or any
combination thereof.

Illustration: Code that centers the four labels in their grid positions:

* Illustration: Spanning of a window component across several grid


positions

- When a window has two components in the first row and only one
component in the second row, the latter component might be centered in its
row, thus occupying two grid positions.
- The programmer can force a horizontal and/ or vertical spanning of grid
positions by supplying the rowspan and columnspan keyword arguments
when adding a component

07/06/23
Wednesday
Types of Window Components and Their Attributes

* GUI programs use several types of window components, or widgets as


they are commonlycalled.

- These include labels, entry fields, text areas, command buttons, drop-
down menus,sliding scales, scrolling list boxes, canvases, and many
others.

*The breezypythongui module includes methods for adding each type of


window component to a window.

* Each such method uses the form:


self.addComponentType(<arguments>)

- When this method is called, breeypythongui

1. Creates an instance of the requested type of window component

2. Initializes the component’s attributes with default values or any values


provided by the programmer

3. Places the component in its grid position (the row and column are
required arguments)

4. Returns a reference to the component


Window components in breezypythongui are listed above

Displaying Images

* Display an image with a caption

- This program adds two labels to the window. One label displays the
image.
The image label is first added to the window with an empty text string.
The program then creates a PhotoImage object from an image file and sets
the image attribute of the image label to this object.

- Second label displays the caption.


The program creates a Font object with a non-standard font and resets
the text label’s font and foreground attributes to obtain the caption shown
in Figure
12/06/2023
Monday

Command Buttons and Responding to Events

* A command button is added to a window just like a label, by specifying


its text and position in the grid.

- A button is centered in its grid position by default.

- The method addButton accomplishes all this and returns an object of


type tkinter.Button .

- Like a label, a button can display an image, usually a small icon, instead
of a string.

- A button also has a state attribute, which can be set to “normal” to


enable the button (its default state) or “disabled” to disable it.

* Illustration 1: Program (buttondemo.py) displays a single label and two


command buttons.
Output:

- The buttons allow the user to clear or restore the label.

When the user clicks Clear, the label is erased, the Clear button is
disabled, and the Restore button is enabled.

When the user clicks Restore, the label is redisplayed, the Restore button
is disabled, and the Clear button is enabled.

Illustration 2: Responding to a button click

* To respond to a button click, the programmer must set the button’s


command attribute.

* There are two ways to do this: either by supplying a keyword


argument when the button is added to the window or, later, by assignment
to the button’s attribute dictionary.
* When the user clicks the Clear button, Python automatically runs the
clear method on the window. Likewise, when the programmer clicks the
Restore button, Python automatically runs the restore method on the
window.

Input and Output with Entry Fields

* An entry field is a box in which the user can position the mouse cursor
and enter a number or a single line of text.

* It allows a GUI program to take input text or numbers from a user and
display text or numbers as output.

Text Fields

* A text field is appropriate for entering or displaying a single-line string


of characters.

* The programmer uses the method addTextField to add a text field to a


window.

- The method returns an object of type TextField , which is a subclass of


tkinter.Entry .

-Required arguments to addTextField are text (the string to be initially


displayed), row , and column .

-Optional arguments are rowspan , columnspan , sticky , width , and


state .

* A text field is aligned by default to the northeast of its grid cell.

* A text field has a default width of 20 characters.

* The programmer can set a text field’s state attribute to “readonly” to


prevent the user from editing an output field.

* The TextField method getText returns the string currently contained in a


text field. Thus, it serves as an input operation.

* The method setText outputs its string argument to a text field.


Illustration : Program (textfielddemo.py) that converts a string to
uppercase. The user enters text into the input field, clicks the Convert
button, and views the result in the output field.
Integer and Float Fields for Numeric Data

* IntegerField and FloatField are used for the input and output of integers
and floating-point numbers, respectively.

* The methods addIntegerField and addFloatField are used to add an


integer and float fields respectively to a window.

- The default width of an integer field is 10 characters, whereas the default


width of a float field is 20 characters.
* The method addFloatField allows an optional precision argument. Its
value is an integer that specifies the precision of the number displayed in
the field.

* The methods getNumber and setNumber are used for the input and
output of numbers with integer and float fields.

Illustration: Take an input integer from a field, computes the square root
of this value, and outputs the result, rounded to the nearest hundredth, to a
second field.
* The program as written will run correctly if the inputs are integers, and
these integers are greater than or equal to 0. If the input text is not an
integer or is a negative integer, Python raises an exception

Using Pop-Up Message Boxes

* When errors arise in a GUI-based program, the program often responds


by popping up a dialog window with an error message. Such errors are
usually the result of invalid input data.

- The program detects the error, pops up the dialog to inform the user, and,
when the user closes the dialog, continues to accept and check input data.

* The square root program raises an exception of type ValueError if the


input datum is not an integer or is a negative integer.

- To recover gracefully from this event, we can modify the code of the
program’s computeSqrt method by embedding it in Python’s try-except
statement.
* In the try clause, our program attempts to input the data, compute the
result, and output the result, as before.

- If an exception is raised anywhere in this process, control shifts


immediately to the except clause.

* Python will raise the ValueError in the getNumber method, if the datum
is not an integer, or in the math.sqrt function, if the integer is negative. In
either case, the except clause traps the exception and allows the user to
correct the input after closing the message box.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy