Python Details
Python Details
Programming
Indira Gandhi National Open University
School of Computer and Information
Sciences (SOCIS)
using Python
IGNOU is one of the participants for the development of courses for this Programme.
Copyright
This course has been developed as part of the collaborative advanced ICT course development
project of the Commonwealth of Learning (COL). COL is an intergovernmental organisation
created by Commonwealth Heads of Government to promote the development and sharing of open
learning and distance education knowledge, resources and technologies.
The Open University of Sri Lanka (OUSL) is the premier Open and Distance learning institution in
the country where students can pursue their studies through Open and Distance Learning (ODL)
methodologies. Degrees awarded by OUSL are treated as equivalent to the degrees awarded by
other national universities in Sri Lanka by the University Grants Commission of Sri Lanka.
The Python Software Foundation is owner of Python. Copyright © 2001-2019 Python Software
Foundation; All Rights Reserved. Reference: https://docs.python. org/
Kivy is an open source Python library for development of applications. Reference: https://kivy.org/
This Programming with Python is a teaching learning resource developed by the Open University
of Sri Lanka using various sources duly acknowledged.
© Open University of Sri Lanka and Commonwealth of Learning, 2018. Except where otherwise
noted, The Programming with Python course material is made available under Creative Commons
AttributionShareAlike 4.0 International (CC BY-SA 4.0) License: https://creativecommons.org/
licenses/by-sa/4.0/legalcode.
For the avoidance of doubt, by applying this license the Commonwealth of Learning does not waive
any privileges or immunities from claims that it may be entitled to assert, nor does the
Commonwealth of Learning submit itself to the jurisdiction, courts, legal processes or laws of any
jurisdiction. The ideas and opinions expressed in this publication are those of the author/s; they are
not necessarily those of Commonwealth of Learning and do not commit the organisation.
Commonwealth of Learning
The Open University of Sri Lanka
4710 Kingsway, Suite 2500, Burnaby
P. O. Box 10250, Nawala, Nugegoda
V5H 4M2, British Columbia, Canada
Sri Lanka
Phone: +1 604 775 8200
Phone: +94 112881481
Fax: +1 604 775 8210
Fax: +94112821285
Email: [email protected]
Email: [email protected]
Website: www.col.org
Website: www.ou.ac.lk
ACKNOWLEDGEMENT BY AUTHORS
The Open University of Sri Lanka (OUSL), Department of Electrical and Computer
Engineering (ECE) wishes to thank those below for their contribution to this course
material and accompanying videos and screencasts:
AUTHORS
Unit 11 NT De Silva (Project Assistant, Dept. of ECE, OUSL)
Units 12 and 13 GSN Meedin (Lecturer, Dept. of ECE, OUSL)
Units 14 and 15 MHMND Herath (Lecturer, Dept. of ECE, OUSL)
Content Editor Language Editor: Reviewer:
DN Koggalahewa (Senior KARD Gunaratne KARD Gunaratne
Lecturer, Sri Lanka Institue (Lecturer, Dept. of ECE, (Lecturer, Dept. of ECE,
of IT) OUSL) OUSL)
Video presenters: Screencasters:
S Rajasingham (Lecturer, Dept. of ECE, MHMND Herath (Lecturer, Dept. of ECE,
OUSL) M Abeykoon (Software Engineer, OUSL) M Abeykoon (Software Engineer,
Duo Software) SN Muhandiram (Associate Duo Software)
Software Engineer, VizuaMatix )
COURSE COORDINATOR
Dr. Sudhansh Sharma,
Assistant Professor
School of Computers and Information Sciences(SOCIS)
Indira Gandhi National Open University(IGNOU),
New Delhi-110068
In this Block the Introduction to the Block along with the Check Your Progress in all the
units, and Answers to Check Your Progress Questions are written and added in 2021, By
Dr. Sudhansh Sharma, Assistant Professor
SOCIS, IGNOU, New Delhi-110068
PRINT PRODUCTION
Mr. Tilak Raj Mr. Yashpal
Assistant Registrar (Publication) Assistant Registrar (Publication)
MPDD, IGNOU, New Delhi MPDD, IGNOU, New Delhi
April, 2021
© Indira Gandhi National Open University, 2021
ISBN-
All rights reserved. No part of this work may be reproduced in any form, by mimeograph or any
other means, without permission in writing from the Indira Gandhi National Open University.
Further information, about the Indira Gandhi National Open University courses may be obtained
from the University’s office at Maidan Garhi, New Delhi-110 068.
Printed and published on behalf of the Indira Gandhi National Open University by Registrar,
MPDD, IGNOU, New Delhi
Laser Composed by Tessa Media & Computers, C-206, Shaheen Bagh, Jamia Nagar, New Delhi
e
BLOCK
3
DATA HANDLING, MOBILE APPLICATION AND
GUI DEVELOPMENT USING PYTHON
UNIT 11
Handling Data with Python 5
UNIT 12
Role of Python in Mobile Application Development 17
UNIT 13
UNIT 14
UNIT 15
3
Data Handling, Mobile
Application & Gui
Development Using
BLOCK INTRODUCTION
Python
Python is the most popular high-level programming language that can be
used for real-world programming. It is a dynamic and object-oriented
programming language that can be used in a vast domain of applications,
especially data handling. Python was designed as a very user-friendly
general-purpose language with a collection of modules and packages and
gained popularity in the recent times. Whenever we think of machine
learning, big data handling, data analysis, statistical algorithms, python is the
only name which comes first in our mind. It is a dynamically typed language,
which makes it highly flexible. Furthermore, creating a database and linking
of the database is very fast and secure. It makes the program to compile and
run in an extremely flexible environment can support different styles of
programming, including structural and object-oriented. Its ability to use
modular components that were designed in other programming languages
allows a programmer to embed the code written in python for any interface.
Due to its enormous features, python has become the first choice of learners
in the field of data science and machine learning.
The content present in this block makes you to learn about the importance of
databases in real world applications and importance of using SQLite with
Python. Firstly, you will learn about integrating database concepts into real
world applications and data management using SQLite. Next, you will learn
how to use these different techniques and when to use them. On completion
of the content, you will be able to integrate various data management
functionalities to Python applications that you will develop while going
through this course.
Further, after going through the content of this block you will learn the role
of Python in mobile application development. Firstly, you will get an insight
to the existing mobile application development environments. Then you will
learn the suitable development environments and different open source
Python libraries available to support these development environments.
Furthermore, this block will list the libraries that you can use in Android
application development using Python. Kivy is one of the frameworks used
by Python programmers to develop mobile applications. At the latter part of
this unit, the steps to follow in setting up the application development
environment will be explained.
Later, by understanding the content covered in this block you will learn the
development of GUI components in Python and Tkinter standard GUI library
that is bundled with python and wxPython libraries. You will also learn
different types of packages available for GUI development.
Developing GUI using kivy is different from Tkinter and wxPython because
Kivy has a different architecture. You will learn how Kivy GUI libraries can
be used in python programming by studying the given programming codes.
Output of each programming code is given before the code snippet. Write and
run codes and check whether the outputs are correct.
4
e Python with kivy cross platform is a very useful method of implementing
GUI for mobile application. Four different types of GUI programming
examples are given to study different areas.
Happy Programming !!
5
Data Handling, Mobile
Application & Gui
Development Using
Python
6
e
UNIT 11 HANDLING DATA WITH PYTHON
11.1 Introduction
11.2 Objectives
11.3 Terminologies
11.4 What is a Database?
11.5 Database Concepts
11.6 Introduction to SQLite
11.6.1 Installing SQLite manager on Firefox
11.6.2 Creating a database Connection
11.7 SQL CRUD statements
11.8 Introduction to database constraints
Video 13: Handling Data in Python
11.9 Summary
11.10 Further Reading
11.1 INTRODUCTION
In this unit you will learn about the importance of databases in real world
applications and importance of using SQLite with Python.
First, you will learn about integrating database concepts into real world
applications and data management using SQLite. Next, you will learn how to
use these different techniques and when to use them.
It is more complicated to write the code to use a database to store data than
Python dictionaries or flat files so there is little reason to use a database
unless your application truly needs the capabilities of a database.
The situations where a database can be quite useful are:
1) When your application needs to make many small random updates within
a large data set,
2) When your data is so large that it cannot fit in a dictionary and you need
to look up information repeatedly, or
3) You have a long-running process that you want to be able to stop and
restart and retain the data from one run to the next.
You can build a simple database with a single table to suit many application
needs, but most problems will require several tables and links/relationships
between rows in different tables. When you start making links between
tables, it is important to do some thoughtful design and follow the rules of
database normalization to make the best use of the database’s capabilities.
Since the primary motivation for using a database is that you have a large
amount of data to deal with, it is important to model your data efficiently so
your programs run as fast as possible.
7
Data Handling, Mobile
Application & Gui
On completion of this unit, you will be able to integrate these data
Development Using management functionalities to Python applications that you develop.
Python
11.2 OBJECTIVES
Upon completion of this unit you will be able to:
• Setup database designing environment for SQLite.
• dentify the constraints when designing a database.
• Create a database using SQLite and connect with a Python application.
• Use appropriate CRUD operations to manipulate data.
11.3 TERMINOLOGIES
DBMS: A DataBase Management System (DBMS) is a computer
software application that interacts with the user, other
applications, and the database itself to capture and analyze
data.
CRUD: create, read, update, and delete (as an acronym CRUD) are
the four basic functions of persistent storage.
SQL SQL constraints are used to specify rules for the data in a
Constraint: table. Constraints are used to limit the type of data that can
go into a table. This ensures the accuracy and reliability of
the data in the table.
You will learn more about integrating database systems into applications in a
later unit. In the following section, we will be discussing about the basic idea
behind the database concepts.
tuple Relation
row
Table
2.2
2.2
attribut
column
import sqlite3
When we create a database table we must tell the database that the names of
each column and the type of data which we are planning to store in each
column.
Various data types supported by SQLite are depict in below table:
Data types
VARCHAR(10),
NVARCHAR(15)
TEXT
INTEGER
FLOAT
BOOLEAN
CLOB
BLOB
TIMESTAMP
NUMERIC(10,5)
VARYING CHARACTER (24)
NATIONAL VARYING CHARACTER(16)
The code to create a database file and a table named ‘StudentDetails’ with
two columns in the database is shown in Example 11.1
Example 11.1
import sqlite3
conn = sqlite3.connect('school.sqlite3')
cur = conn.cursor()
Select
C
Update U
R Database
Create S
O
Delete R
Once we have the cursor, we can begin to execute commands on the contents
of the database using the execute() method.
Database commands are expressed in a special language that has been
standardized across many different database vendors to allow us to learn a
single database language. That is called Structured Query Language or SQL
for short.
The first SQL command removes the StudentDetails table from the database
if it exists.
Then the second command will creates a table named ‘StudentDetails’ with a
text column named ‘StudentName’ and an integer column named
‘StudentID’.
cur.execute('CREATE TABLE StudentDetails (StudentName
TEXT, StudentID INTEGER)')
Select Command
Then we use 'SELECT' command to retrieve rows and columns from a
database table. The SELECT statement lets you specify which columns you
would like to retrieve as well as a WHERE clause to select which rows you
would like to see. It also allows an optional ORDER BY clause to control the
sorting of the returned rows.
Using * indicates that you want the database to return all of the columns for
each row that matches the WHERE clause.
You can also request that the returned rows be sorted by one of the fields as
shown in Example 11.3.
Example 11.3
Delete Command
To remove a row, you need to use 'WHERE' clause on a 'DELETE' statement.
The WHERE clause determines which rows are to be deleted:
Example 11.4
12
e
Update Command Handling Data
with Python
The UPDATE statement specifies a table and then a list of fields and values to
change after the SET keyword and then an optional WHERE clause to select
the rows that are to be updated. If a WHERE clause is not specified, it
performs the UPDATE on all of the rows in the table.
It is possible to UPDATE a column or columns within one or more rows in a
table using 'UPDATE' statement as in Example 11.5:
Example 11.5
cur.execute(UPDATE StudentDetails SET StudentName =
'XYZ Perera' WHERE StudentID = 15033)
conn.commit()
We indicate that the People table must be UNIQUE. We also indicate that the
combination of the two numbers in each row of the Follows table must be
unique. These constraints keep us from making mistakes such as adding the
same relationship more than once.
We can take the advantage of these constraints in the following code:
Example 11.9
cur.execute('''INSERT OR IGNORE INTO People (name,
retrieved)
VALUES ( ?, 0)''', ( friend, ) )
14
e
A logicalkey is a key that the “real world” might use to look up a row. In our Handling Data
example data model, the name field is a logical key. It is the screen name for with Python
the user and we indeed look up a user’s row several times in the program
using the name field. You will often find that it makes sense to add a
UNIQUE constraint to a logical key. Since the logical key is how we look up a
row from the outside world, it makes little sense to allow multiple rows with
the same value in the table.
A primarykey is usually a number that is assigned automatically by the
database. When we want to look up a row in a table, usually searching for the
row using the primary key is the fastest way to find the row. Since primary
keys are integer numbers, they take up very little storage and can be
compared or sorted very quickly.
A foreignkey is usually a number that points to the primary key of an
associated row in a different table. An example of a foreign key in our data
model is the from_id.
We are using a naming convention of always calling the primary key field
name id and appending the suffix _id to any field name that is a foreign key.
Video 13: Handling Data in Python
This video will further explain data manipulation in Python. You may watch
this Video with screencast an attempt Activity11.1
URL : https://youtu.be/gEMPzwcSfC4
Activity11.1
• Create a database using SQLite called ‘ABC_Organization’
• Create a table inside that database and name it ‘Employee’,
• Create following fields in ‘Employee’ table
EmpFirstName Text
EmpLastName Text
Gender Boolean
NICNo varchar(100)
15
Data Handling, Mobile
Application & Gui
• Insert an employee detail to the table (ex: EmployeeID : 105524,
Development Using EmpFirstName : PQR, EmpLastName : Fernando, Gender : 1, NICNo :
Python 895562987V)
• Update the first name of the employee to ‘PQWR’ where employee id is
105524
• Select fields EmpFirstName, EmpLastName as EmployeeName and
NICNo from Employee table
Check Your Progress
Q-1 Write SQL Crud statements with example for each.
Q-2 What are integrity constraints? Briefly discuss various types of integrity
constraints, Give example of each.
11.9 SUMMARY
This unit covered a lot of ground to give you an overview of the basics of
using a database in Python it also provide few examples to create database
connection and to write SQL commands. Further this unit discussed how to
integrate data management functionalities to Python applications.
16
e
UNIT 12 ROLE OF PYTHON IN MOBILE
APPLICATION DEVELOPMENT
12.1 Introduction
12.2 Objectives
12.3 Terminologies
12.4 Mobile Application Development Environments
12.5 Uses of Python in Mobile Application Development
12.6 Open Source Python Libraries
12.7 Kivy
12.8 Summary
12.9 Further Reading
12.10 Answer to check your progress
12.1 INTRODUCTION
In this unit we are going to learn the role of Python in mobile application
development. First part of this unit will give you an insight to the existing
mobile application development environments. Then you will learn the
suitable development environments and different open source Python
libraries available to support these development environments.
Furthermore, this unit will list the libraries that you can use in Android
application development using Python. Kivy is one of the frameworks used
by Python programmers to develop mobile applications. At the latter part of
this unit, the steps to follow in setting up the application development
environment will be explained.
12.2 OBJECTIVES
Upon completion of this unit you will be able to:
• identify different mobile application development environments
• explain the use of open source Python libraries for rapid development of
applications
• describe the use of python libraries available for android application
development
• illustrate the Kivy app architecture using a diagram
• set up the application development environment using Kivy
17
Data Handling, Mobile
Application & Gui
Development Using
12.3 TERMINOLOGIES
Python
Kivy: an open source Python library for developing mobile apps and
other multitouch application software
18
e
programming language for the language of the framework to communicate Role of Python
in Mobile
with the native code of different platforms. Application
Development
The top tools used for cross-formatting mobile application development are
RhoMobile, PhoneGap, Appcelerator, Sencha Touch, MoSync, Whoop,
WidgetPad, GENWI, AppMakr, Mippin, SwebApps, MobiCart, etc.
20
e
• WXPython - WXPython is a GUI toolkit for Python programming Role of Python
in Mobile
language. This is implemented as a Python extension module (native Application
code) that wraps the wxWidgets cross platform GUI library, which is Development
written in C++.
• PyQT and PySide – These are the two popular Python bindings for the
Qt cross-platform GUI/XML/SQL C++ framework. Qt is a cross-
platform application framework that is used for developing application
software that can be run on various software and hardware platforms
with little or no change in the underlying codebase, while still being a
native application with native capabilities and speed.
• QPython - QPython is a script engine which runs Python programs on
android devices.
• VPython - VPython allows users to create objects such as spheres and
cones in 3D space and displays these objects in a window
• TkInter - TkInter is Python's standard GUI (Graphical User Interface)
package.
As you can see there are many open source libraries to develop different
types of applications for multiple platforms. Kivy is one of such platform
facilitate application development for multiple platforms. We will learn about
Kivy in detail in the next section.
12.7 KIVY
Kivy allows you to write your code once and have it run on different
platforms. This section will provide you a guide to get the tools you need,
understand the major concepts and learn best practices. As this is an
introduction, pointers to more information in developing an application will
be given in Unit 13.
Using Kivy on your computer, you can create applications that run on:
• Desktop computers: OS X, Linux, Windows.
• iOS devices: iPad, iPhone.
• Android devices: tablets, phones.
• Any other touch-enabled devices supporting TUIO (Tangible User
Interface Objects)
Kivy Architecture
Let us look at the architectural view of Kivy. Knowing the Kivy architecture
will help you when developing applications using Kivy platform.
21
Data Handling, Mobile
Application & Gui
Development Using
Python
class MyApp(App):
def build(self):
return Label(text='Hello world')
if name == ' main ':
MyApp().run()
You can save this to a file, main.pyfor example, and run it.
If you saved your file inside the Python installation folder, you need to use
the following command to run the program.
python main.py
You will find the output of this program as given below.
• In order to use Kivy, it’s required to importkivy first; line 1 shows how to
import kivy.
• The term require can be used to check the minimum version required to
run a Kivy application. To run this program you need to have '1.0.6'
• Line 3 is required so that the base class of your App inherits from the App
class. It’s present in the kivy_installation_dir/kivy/app.py
• In line 4, the uixmodule is the section that holds the user interface
elements like layouts and widgets.
The above program has the following three parts.
• In line 5, sub-classing the App class
24
e
This is where we are defining the Base Class of our Kivy App. You Role of Python
in Mobile
should only need to change the name of your app MyApp in this line. Application
• In line 6, implementing its build() method so it returns Development
25
Data Handling, Mobile
Application & Gui
• In line 10 we set the color for the canvas. We use the random values we
Development Using
from random import random #Line1
Python
from kivy.app import App
class MyPaintWidget(Widget):
def on_touch_down(self,touch):
color = (random(,1,1) #Line8
with self.canvas:
Color(*color, mode='hsv') #Line 10
d = 30.
Ellipse(pos=(touch.x-d/2,touch.y-d/2),size=(d,d))
touch.ud['line']=Line(points=(touch.x,touch.y))
def on_touch_move(self,touch):
touch.ud['line'].points+=[touch.x,touch.y]
class MyPaintApp(App):
def build(self):
parent = Widget() #Line 18
self.painter = MyPaintWidget() #Line 19
clearbtn = Button(text='Clear') #Line 20
clearbtn.bind(on_release=self.clear_canvas) #Line 21
parent.add_widget(self.painter) #Line 22
parent.add_widget(clearbtn) #Line 23
return parent
def clear_canvas(self,obj): #Line 25
self.painter.canvas.clear() #Line 26
generated only at this time and feed them to the colour class using
Python’s tuple unpacking syntax.
• In Line 18, parent = Widget()is used to create a
• dummy Widget()object as a parent for both our painting widget and the
button we’re about to add.
• In line 19, we create our MyPaintWidget()as usual, only this time we don’t
return it directly but bind it to a variable name.
• In line 20, We create a button widget. It will have a label on it that
displays the text ‘Clear’.
In line 21,we bind the button’s on_releaseevent (which is fired when the button
is pressed and then released) to the callback
function clear_canvasdefined on below on lines 25 & 26.
We set up the widget hierarchy in line 22 and 23 by making both the painter
and the clearbtn children of the dummy parent widget. That means painter and
clearbtn are now siblings in the usual computer science tree terminology.
Up to now, the button did nothing. It was there, visible, and you could press
it, but nothing would happen. We change that in lines 25 and 26. We create a
small, throw-away function that is going to be our callback function when the
button is pressed. The function just clears the painter’s canvas’ contents,
making it black again.
26
e
Activity12.1 Role of Python
in Mobile
• List down and briefly explain the use of five open source Python Application
Development
libraries which are not mentioned in the unit.
Check Your Progress
Q-1 What is the utility of Battery stats and Battery Historian tools? How one can
use python scripts to work with Battery stats and Battery Historian? Discuss.
Q-2 draw the architecture of Kivy and discuss the functionality of various
components involved in the architecture.
12.8 SUMMARY
Different types of Python libraries available for rapid application
development were explained in this unit. Furthermore the details of Kivy
application life cycle and the Kivy architecture were explained. Steps to be
followed when writing a Python application using Kivy were explained with
examples at the end of the unit.
In the next section you will learn how the developed applications using Kivy
can be packaged to run on Android devices.
28
e
UNIT 13 MOBILE APPLICATION
DEVELOPMENT WITH PYTHON
13.1 Introduction
13.2 Objectives
13.3 Terminologies
13.4 Android Mobile Application Development using Kivy
13.5 Buildozer Tool
13.6 Packaging with Python-for-android
13.7 Packaging your application for the Kivy Launcher
13.8 The Kivy Android Virtual Machine
13.9 Summary
13.10 Further Reading
13.11 Answer to check your progress
13.1 INTRODUCTION
In the previous unit you learnt to set up the development environment for a
Kivy application. In this unit you will be learning to develop an application
using Kivy and to package it to run on Android devices.
13.2 OBJECTIVES
Upon completion of this unit you will be able to:
• Develop a Python application using Kivy
• Build the developed application and run it on Android device
13.3 TERMINOLIGES
bootstrap: A bootstrap is a class consisting of few basic
components (i.e. with SDL2, Pygame, Webview etc.)
Virtual Machine(VM): A virtual machine is an operating system or
application environment that is installed on software.
• The second method is to run the Kivy app without a compilation step
with the Kivy Launcher app
Then you need to install the dependencies you need. Some of the
dependencies are given below.
30
e
• git Mobile
Application
• ant Development
With Python
• python2
• cython
• a Java JDK
• zlib
• libncurses unzip
• virtualenv ( can be installed via pip)
• ccache (optional)
You need to download and unpack the Android SDK and NDK to a directory
(let’s say $HOME/Documents/)
Then, you can edit your ~/.bashrc or other favorite shell to include new
environment variables necessary for building on android
If anything goes wrong and you want to clean the downloads and builds to
retry everything it is required to run the following command.
p4a clean_all
Activity13.1
• Download the Kivy demos for Android by visiting
https://storage.googleapis.com/google-code-archive-
downloads/v2/code.google.com/kivy/kivydemo-for-android.zip
• Unzip the contents and go to the folder `kivydemo-for-android`
• Copy all the subfolders here to /sdcard/kivy
• Run the Kivy launcher and select one of the Pictures, Showcase,
Touchtracer, Cymunk or other demos
Check Your Progress
Q-1 Compare Buildozer and Kivy Launcher.
13.9 SUMMARY
In this unit you learned how to package your Python application to run on
Android devices. In the next section let’s learn about how to design the
Graphical User Interfaces(GUI) for mobile applications using Python
libraries
34
e
14.1 Introduction
14.2 Objectives
14.3 Terminologies
14.4 Graphical User interface (GUI)
14.5 Different types of packages for GUI development in Python
14.6 Tkinter (GUI toolkit that comes with Python)
Video 14: Creating GUI for Python with Tkinter
14.7 GUI with wxPython
Video 15: Python GUI with WxFrame
14.8 Summary
14.9 Referance
14.10 Answer to check your progress
14.1 INTRODUCTION
In this unit you will learn components of GUI and Tkinter standard GUI
library that is bundled with python and wxPython libraries. You will also
learn different types of packages available for GUI development. There are
eight (8) examples to study Tkinter standard library and three (3) examples to
study wxPython.
Line numbers before the programming code are included for easy references.
But do not to include line numbers when you code in the text editor. Essential
lines in the code are described after the program code.
14.2 OBJECTIVES
Upon completion of this unit you will be able to:
• Describe Graphical User Interface (GUI) and its components.
• Idetify different types of packages for python GUI implement.
• Demonstrate the skills of programming in Tkinter GUI standard library.
• Demonstrate GUI programming with wxPython cross platform libraries.
• Aply event driven programming for GUI using Tkinter and wxPython
libraries
35
Data Handling, Mobile
Application & Gui
Development Using
14.3 TERMINOLOGIES
Python
GUI: Graphical User Iterface
widget: building blocks that make up an application in a GUI
36
e
widget - the general word for visual building blocks to interact an Activityin Python
Graphical User
GUI. Interface
Development
Layouts -The way you arrange the widgets in a GUI.
Parent, child – A relationship of parent and child is created for any crated
widget. For example, when a check button placed on a frame, frame becomes
parent and check button becomes child.
37
Data Handling, Mobile
Application & Gui
Example 14.1 Tkinter GUI window
Development Using
Python 1 #/user/bin/python
2 import Tkinter as tk1
3 tp=tk1.Tk()
4 # Codes for widgets
5 tp.mainloop()
1 Self executing script, in linux you can run by ‘ ./’ rather than
typing python <file name>.py
2 Import Tkinter library
3 Tkinter Tk window is assigned to top.
4 Comment
5 Main loop is started and waiting for mouse and key board actoins.
Tkinter Widgets
Widget is a graphical user interface controls to interact between user and
computer. Tkinter gives different types of controls such as buttons, labels and
text boxes used in a GUI application. Tkinter widgets are described in the
following table. Most widegts can be seen in figure 14.1.
Widget Widget image Description
38
e Checkbutton Number of options can be selected using Python
Graphical User
check buttons. More than one choice can
Interface
be selected in grouped options Development
Entry A line of text can be entered using entry
widget
Frame A container to insert and organize other
widgets.
Label Caption of single line can be displayed
using label. Images may also insert to
label.
39
Data Handling, Mobile Option Description
Application & Gui
Development Using Active Background color when the cursor is on the button.
Python background
Active Foreground color when the cursor is on the button.
foreground
Bd width of the border. Default is 2.
Bg Normal background color.
command Calling function or method when the button is clicked.
Fg Colour of the text (foreground)
Font Type of the font used for label of the button.
Height Height of the text or image
Highlight The color of the focus highlight when the widget has focus.
color
Image Image to be attached and display
Justify Alignment of the text line - justify
CENTER Alignment of the text line - center
Padx Horizontal length of button through x axis can be sat.
Pady vertical length of button through x axis can be sat.
Relief Border style- button appear as SUNKEN, RAISED, GROOVE,
or RIDGE
State Can set the button as DISABLED or ACTIVE. It active when
the button is over.
underline Underline the relevant character, Default is -1, which means no
character is underlined.
Width Set the width of the button.
wraplength If this value is set to a positive number, the text lines will be
wrapped to fit within this length.
Example 14.2. This python program illustrates how to work with button.
1 #!/usr/bin/python
2
3 import Tkinter as tk
4 import tkMessageBox as bx
5 tp=tk.Tk()
6 def exbutton():
7 bx.showinfo("Python button example","Hello
8 World")
9 B=tk.Button(tp,text="Press this
10 button",command=exbutton)
B.pack()
tp.mainloop()tp.mainloop()
Figure 14.3. Message “Hello World” will appear when "Press this button" is
clicked
The output of the above program is shown in fig 14.3. When the button called
40 ‘Press this button’ is clicked, the message box ‘Hello World’ will appear.
e
Description of codes in line numbers of the program Python
Graphical User
Interface
9. import tkMessageBox module
Development
10. a function called exbutton
11. Text of the button is “Press this button” and button is assigned to
“B”. Function exbutton is invoked by clicking button.
Parameters:
• master: the parent window.
• options: : List of ususally used options are given below
Option Description
Bg background color
Bd Size of the border
The size of the border around the indicator. Default is 2
pixels.
command Invoking function when user change content
cursor Cursor of the mouse will change according to the given
cursor name (arrow, dot etc).
font Type of the font
exportselection By default, if you select text within an Entry widget, it is
automatically exported to the
clipboard To avoid this exportation, use exportselection=0.
Fg The color used to render the text.
highlightcolor The color of the focus highlight when the checkbutton has
the focus.
justify If the text contains multiple lines, this option controls how
the text is justified: CENTER, LEFT, or RIGHT.
relief With the default value, relief=FLAT, the checkbutton does
not stand out from its background. You may set this option
to any of the other styles .
Selectbackground Background color of the selected text
selectborderwidth The width of the border to use around selected text. The
default is one pixel.
selectforeground The foreground (text) color of selected text.
show Normally, the characters that the user types appear in the
entry. To make a .password. entry that echoes each
character as an asterisk, set show="*".
41
Data Handling, Mobile state The default is state=NORMAL, but you can use
Application & Gui
Development Using state=DISABLED to gray out the control and make it
Python unresponsive. If the cursor is currently over the
checkbutton, the state is ACTIVE.
Text variable In order to be able to retrieve the current text from your
entry widget, you must set this option to an instance of the
StringVar class.
Width The default width of a checkbutton is determined by the
size of the displayed image or text. You can set this option
to a number of characters and the checkbutton will always
have room for that many characters.
Xscroll command If you expect that users will often enter more text than the
onscreen size of the widget, you can link your entry widget
to a scrollbar.
When the above code is executed, it produces the output as show in the
Figure 14.4:
Parameters
master: This represents the parent window.
options: Here is the list of most commonly used options for this widget.
These options can be used as key-value pairs separated by
commas.
42
e Python
Option Description Graphical User
anchor This options controls where the text is positioned if the widget Interface
Development
has more space than the text needs. The default is
anchor=CENTER, which centers the text in the available space.
Bg The normal background color displayed behind the label and
indicator.
Bitmap Set this option equal to a bitmap or image object and the label
will display that graphic.
Bd The size of the border around the indicator. Default is 2 pixels.
Cursor If you set this option to a cursor name (arrow, dot etc.), the
mouse cursor will change to that pattern when it is over the
checkbutton.
Font If you are displaying text in this label (with the text or text
variable option, the font option specifies in what font that text
will be displayed.
Fg If you are displaying text or a bitmap in this label, this option
specifies the color of the text. If you are displaying a bitmap, this
is the color that will appear at the position of the 1-bits in the
bitmap.
Height The vertical dimension of the new frame.
Image To display a static image in the label widget, set this option to an
image object.
Justify Specifies how multiple lines of text will be aligned with respect
to each other: LEFT for flush left, CENTER for centered (the
default), or RIGHT for right-justified.
Padx Extra space added to the left and right of the text within the
widget. Default is 1. pady Extra space added above and below
the text within the widget. Default is 1.
Relief Specifies the appearance of a decorative border around the label.
The default is FLAT; for other values. text To display one or
more lines of text in a label widget, set this option to a string
containing the text. Internal newlines ("\n") will force a line
break.
Textvariable To slave the text displayed in a label widget to a control variable
of class StringVar, set this option to that variable.
Under You can display an underline (_) below the nth letter of the text,
Line counting from 0, by setting this option to n. The default is
underline=-1, which means no underlining.
Example 14.4. This program illustrates how to program using label and grid.
1 import Tkinter as tk
2 m=tk.Tk()
3
4 tk.Label(m,text='First',bg="red").grid(row=0,column=0)
5 tk.Label(m,text='Second',bg="blue").grid(row=0,column=1)
tk.Label(m,text='Third',bg="green").grid(row=1,column=0)
m.mainloop()
The output of the above program is illustrated in the figure 14.5. Remember
you should write line 5 in one line.
43
Data Handling, Mobile
Application & Gui
Development Using
Python
Setting rows and columns of grid are shown in following table. Any widget
like entry, image can be arranged in grids.
Row=0, coloumn=0 Row=0, coloumn=1
Row=1, coloumn=0 Row=1, coloumn=1
Line number 3 of the above code is a Label and “Your sex:” is displayed.
There are two checkbuttons one for “male” and other for “female”.
Mainloop() waits for mouse and keyboard.
Grid property set label and check buttons 3 top rows of the “m” window.
Checkbutton for selection with align to the west
Checkbutton can be aligned using stick parameter in grid object. The
program to explain the grid sticky option of checkbutton is given in example
14.6 and the output screen is shown in figure 14.7.
Example 14.6 This program explains how to program using checkbutton with
grid sticky option.
44
e 1 from Tkinter import * #import Tkinter module
2 m=Tk() # Tk window assigned to m
3 Label(m,text="Your sex: ") .grid(row=0,sticky=W)
4 Checkbutton(m,text="male",variable=var1).grid(row=1,sticky=W)
5 Checkbutton(m,text="female",variable=var2).grid(row=2,sticky=W)
6 mainloop() #starts main loop- waiting for mouse and key board
(a) (b)
Male and female checkbuttons of figure 14.7 (a) are not aligned and figure
11.7 (b) shows the aligned checkbuttons. This can be done with sticky option
of grid manager. The above example has sticky=W i.e. aligned to left side.
Likewise, following options also can be used.
N, E, S, W, NE, NW, SE, and SW
Assigning checkbutton selection to variable
Example 14.7 This program describes how selections of checkbuttons are
assigned to variables.
45
Data Handling, Mobile Listbox
Application & Gui
Development Using
Python Listbox is the Tkinter standard list box to facilitate a list. List of provinces in
Sri Lanka created by using tkinter GUI library is shown in the figure 14.9.
User can select a province from the list of provinces.
Figure 14.9: List of provinces, user can select either province from the list
Python code for the output of the Figure 14.9 is given in example 14.8.
Example 14.8 program to describe listbox.
Line 3: l1 instance is derived from the Label class. Text of the label “l1” is
"Provinces of Sri Lanka".
l1=Label(master,text="Provinces of Sri Lanka")
46
e Python
Line 7: Append an item to the list. Graphical User
Interface
listbox.insert(END, "Central") Development
47
Data Handling, Mobile
Application & Gui
Development Using
Python
Line 3: Create a top level window as object of wx.Frame class. Caption and
size parameters are given in constructor.
window = wx.Frame(None,title="wxPython Frame",size=(300,200))
Line 4: Although other controls can be added in Frame object, their layout
cannot be managed. Hence, put a Panel object into the Frame.
panel=wx.Panel(window)
48
e
wx.Panel
wx.Panel class is derived from the wx.Window class. This class is inserted to
the wx.Frame class. Widgets such as button, text box etc. can be placed in
this class.
Sub classing the Frame -“Hello World” program with class
The GUI output in Figure 14.12 has a frame with the title “Hello World”.
49
Data Handling, Mobile
Application & Gui
Example 14.10 Program to create frame class called “Frame”.
Development Using 1 import wx
Python 2 class Frame(wx.Frame):
3 def __init__(self, title):
4 wx.Frame.__init__(self, None, title=title, size=(350,200))
5
6 app = wx.App(redirect=True)
7 top = Frame("Hello World")
8 top.Show()
9 app.MainLoop()
Line 3: The above title is received to the following class Frame and initiated
with the title.
def __init__(self, title):
Line 4: title of the line 3 is received to the wx.Frame and it initiated with
wx.Frame.__init__(self, None, title=title, size=(350,200))
50
e
Output of the Figure 14.13 is produced by running the code of the example
14.11.
Example 14.11 program code describes how to use textcontrols and
buttons of wxPython
1 import wx
2 class wxcal(wx.Frame):
3 def __init__(self, title):
4 wx.Frame.__init__(self, None, title=title,
pos=(150,150), size=(350,200))
5 panel = wx.Panel(self)
6 self.fno=wx.TextCtrl(panel, value="", pos=(10, 2),
size=(50,-1))
7 self.sno=wx.TextCtrl(panel, value="", pos=(70, 2),
size=(50,-1))
8 self.result= wx.TextCtrl(panel, -1,"", pos=(130, 2), .
size=(50,-1))
self.addbtn=wx.Button(panel, wx.ID_NONE, "+", pos =
9 (10,50) ,size=(50,-1))
self.addbtn.Bind(wx.EVT_BUTTON,self.addbtnclick)
10
self.subbtn=wx.Button(panel, wx.ID_NONE, "-",pos =
11
(70,50), size =(50,-1))
self.subbtn.Bind(wx.EVT_BUTTON,self.subbtnclick)
12
self.mulbtn=wx.Button(panel, wx.ID_NONE, "*", pos =
13
(130,50), size=(50,-1))
self.mulbtn.Bind(wx.EVT_BUTTON,self.mulbtnclick)
14
def addbtnclick(self,event):
15
self.result.SetValue(str(float(self.fno.GetValue())+
16
float(self.sno.GetValue()))
def subbtnclick(self,event):
17
self.result.SetValue(str(float(self.fno.GetValue())-
18
float (self.sno.GetValue())))
def mulbtnclick(self,event):
19
self.result.SetValue(str(float(self.fno.GetValue())*
20
float(self.sno.GetValue())))
app = wx.App(redirect=True)
21
top = wxcal("WX Calulator")
22
top.Show()
23
app.MainLoop()
24
Line 5: “panel” is a type of “wx.Panel” class. All the widgets such as text,
buttons are placed in panel. 51
Data Handling, Mobile panel = wx.Panel(self)
Application & Gui
Development Using
Python Line 6 to 8: Two (2) text boxes (wx. TextCtrl) named “fno” and “sno” are
placed in panel and their positions and sizes are specified as follows. There is
another text box named “result” is also placed in specified position and size.
self.fno=wx.TextCtrl(panel, value="", pos=(10, 2), size=(50,-1))
self.sno=wx.TextCtrl(panel, value="", pos=(70, 2), size=(50,-1))
self.result= wx.TextCtrl(panel, -1,"", pos=(130, 2), size=(50,-1))
Line 10 to 11: Button for addition named “addbtn” is a wx.Button class type.
Text of the button is “+” and position and size is as follows. This button has
no identification ( wx.ID_NONE). This button is bind to the method
“addbtnclick” on the click event of the button (wx.EVT_BUTTON ).
self.addbtn=wx.Button(panel, wx.ID_NONE, "+",pos=(10,50),size=(50,-1))
self.addbtn.Bind(wx.EVT_BUTTON,self.addbtnclick)
Line 13 to 17: Program codes for buttons for subtraction and multiplication
and their bindings.
self.subbtn=wx.Button(panel, wx.ID_NONE, "-",pos=(70,50),size=(50,-1))
self.subbtn.Bind(wx.EVT_BUTTON,self.subbtnclick)
Line 19 to 26: Methods to add, subtract and multiply values of fno and sno
and assigned to result are coded here.
def addbtnclick(self,event):
self.result.SetValue(str(float(self.fno.GetValue())+float(self.sno.GetV
alue())))
def subbtnclick(self,event):
self.result.SetValue(str(float(self.fno.GetValue())-
float(self.sno.GetValue())))
def mulbtnclick(self,event):
self.result.SetValue(str(float(self.fno.GetValue())*float(self.sno.Get
Value())))
Example 14.12 Program to display window and circle with red background
1 import wx
2 class drawgeo(wx.Frame):
3 def __init__(self, parent, title):
4 super(drawgeo, self).__init__(parent, title=title,size=(500,300))
self.InitUI()
5
def InitUI(self):
6 self.Bind(wx.EVT_PAINT, self.drawcle)
7
def drawcle(self,w):
8 dc = wx.PaintDC(self)
9 color=wx.Colour(255,0,0)
10 b=wx.Brush(color)
11 dc.SetBrush(b)
12 dc.DrawCircle(300,125,50)
13 app1 = wx.App()
14 top=drawgeo(None,"Draw circle")
15 top.Show()
16 app1.MainLoop()
17
The above window and circle with red background can be programmed by
using the following program. In this program, initially, create instance of wx
app and activate a wx.frame custom class to draw the circle.
Now we will study program code lines in the above program. For easy
reference, program is numbered at the left hand side column to the program.
1 import wx
Import wxPython modules into the program
16 app1 = wx.App()
Create an instance of wx app called app1
17 top=drawgeo(None,"Draw circle")
53
Data Handling, Mobile Create an instance of the custom class of wx.Frame named “drawgeo” with
Application & Gui
Development Using the title “Draw circle".
Python
18 top.Show()
Show the class “top”.
2 class drawgeo(wx.Frame):
Create a wx.Frame class named “drawgeo”
5 self.InitUI()
7 def InitUI(self):
Define InitUI() method
8 self.Bind(wx.EVT_PAINT, self.drawcle)
“drawcle” method of the class drawgeo is bound to the wx.EVT_PAINT event.
10 def drawcle(self,w):
Define the method “drawcle()”
11 dc = wx.PaintDC(self)
wx.PaintDC(self) is used to draw graphics in a client area.
12 color=wx.Colour(255,0,0)
Create an instance of wx.Colour called “color” whose colour is (255,0,0). i.e.
red.
1 b=wx.Brush(color)
3
Create an instance of wx.Brush called “b” whose colour is “color”. wx.Brush is
used to fill
background colur of the object.
14 dc.SetBrush(b)
Set the brush of the wx.PaintDC class called “dc”.
15 dc.DrawCircle(300,125,50)
Draw the circle with x axis point, y axis point and radius
54
e
Python
wxPython GUI visual Designer tools Graphical User
Interface
Coding GUI windows is a very difficult and time cosuming effort. Therefore, Development
there are few visual GUI designer tools available for rapid and quick GUI
application development. They are wxFormBuilder, wxDesigner, wxGlade,
BoaConstructor, gui2py.
Activity14.1
1) Write a GUI program using Tkinter libraries to input two boolean values
(0 or 1) and select a boolean operation from set of boolean operations
AND, OR, NAND, NOR, XOR. Result should be printed in a text box
next to the boolean selection box.
2) Write a GUI program using wxPython libraries to input 2 boolean values
(0 or 1) and select a boolean operation from set of boolean operations
AND, OR, NAND, NOR, XOR. Result should be printed in a text box
next to the boolean selection box.
Check Your Progress
Q-1 Write Tkinter lines of codes to embed following on a form
a) Label
b) Check Button
c) Text entry
d) Button
Q-2 Classify the modules and sub-modules in wxPython.
14.8 SUMMARY
In this unit you learned to identify elements of GUI, different types of python
related packages for GUI development, GUI implement using Tkinter
standard library and wxPython. Then you learned how to invoke widgets of
GUI with methods in user defined classes.
55
Data Handling, Mobile
Application & Gui
Development Using
UNIT 15 GUI PROGRAMMING USING
Python KIVY LIBRARIES
Structure
15.1 Introduction
15.2 Objectives
15.3 Basic GUI programming (user password GUI
15.4 Kivy Layouts and Widgets
15.5 Kv language
15.6 Developing a Calculator using python and kivy
15.7 Develop a Calculator using python and kv language
15.8 GUI with check boxes
15.9 Summary
15.10 Further Reading
15.11 Answer to check your progress
15.1 INTRODUCTION
Developing GUI using kivy is different from Tkinter and wxPython because
Kivy has a different architecture. You will learn how Kivy GUI libraries can
be used in python programming by studying the given programming codes.
Output of each programming code is given before the code snippet. Write and
run codes and check whether the outputs are correct.
Python with kivy cross platform is a very useful method of implementing
GUI for mobile application. Four different types of GUI programming
examples are given in this unit to study different areas when you want to run
a python GUI with Kivy libraries using widgets, layouts, running with only
python or combined with python and Kv language.
15.2 OVERVIEW
Upon completion of this unit you will be able to:
• List type of layouts and widgets in Kivy libraries.
• Describe how to program by arranging and inserting widgets into grid
layout.
• Describe calling methods when interacting with widgets.
• Describe programming with combining python and Kv language
56
e Gui
15.3 BASIC GUI PROGRAMMING (USER Programming
Using Kivy
PASSWORD GUI) Libraries
A sample user password entry GUI is shown in Figure 15.1 and it includes
two labels and two text entry boxes in a two column gridlayout. Only the
GUI shown in figure 15.1 is displayed and no other functions are executed
when running the programming code.
Example 15.1 When you run the program given below, GUI of the figure
15.1 can be obtained.
Now let us analyse the above program code. Line numbers are added for easy
referance.
Line 1 to 4: importing the necessary Kivy GUI libraries (App, gridlayout,
label and textinput).
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
Line 6: inbuilt class “GridLayout” has used for the base class for the class
“LoginScreen”.
class LoginScreen(GridLayout):
self.add_widget(Label(text='User Name'))
self.username = TextInput(multiline=False)
self.add_widget(self.username)
self.add_widget(Label(text='password'))
self.password = TextInput(password=True,
multiline=False)
self.add_widget(self.password)
In kivy, GUI can be implemented with two types of reusable user interfaces,
layouts and widgets.
58
e Gui
15.5 KV LANGUAGE Programming
Using Kivy
Libraries
Mobile GUI applications with kivy libraries can be coded in two different
methods. In first method, functions, classes, widgets and their properties are
coded in the same python file. This method is described with examples in
section 15.1 and 15.4.
In the second method, functions and classes of application are coded in a
python file. Extension of this file is .py. Widgets and their properties are
coded in a kv file. Extension of this file is .kv. Therefore, logic of the
application and its user interface can be separated clearly. GUI applications
can be changed easily to suit user's requirements by doing this way. This
method is described with examples in sections 15.5 and 15.6.
59
Data Handling, Mobile 1 from kivy.app import App
Application & Gui 2 from kivy.uix.button import Button
Development Using 3 from kivy.uix.button import Label
Python 4 from kivy.uix.gridlayout import GridLayout
5 from kivy.uix.textinput import TextInput
6 from kivy.uix.widget import Widget
7
8 class rootwd(GridLayout):
9 def __init__(self,**kwargs):
10 super().__init__(**kwargs)
11 self.cols = 3
12 self.add_widget(Label(text='First Number'))
13 self.add_widget(Label(text='Second Number'))
14 self.add_widget(Label(text='Result'))
15 #
16 self.fno = TextInput(multiline=False,font_size=30)
17 self.add_widget(self.fno)
18 #
19 self.sno = TextInput(multiline=False,font_size=30)
20 self.add_widget(self.sno)
21 #
22 self.tno = TextInput(multiline=False,font_size=30)
23 self.add_widget(self.tno)
24 self.display=self.tno
25 #
26 btnadd=Button(text="+",font_size=30)
27 self.add_widget(btnadd)
28 btnadd.bind(on_press=self.btnaddcal)
29
30 btnsub=Button(text="-",font_size=30)
31 self.add_widget(btnsub)
32 btnsub.bind(on_press=self.btnsubcal)
33
34 btnmul=Button(text="*",font_size=30)
35 self.add_widget(btnmul)
36 btnmul.bind(on_press=self.btnmulcal)
37
38 def btnaddcal(self,instance):
39
40 self.tno.text=str(float(self.fno.text)+float(self.sno.text))
41 def btnsubcal(self,instance):
42 self.tno.text=str(float(self.fno.text)-float(self.sno.text))
43
44 def btnmulcal(self,instance):
45
46 self.tno.text=str(float(self.fno.text)*float(self.sno.text))
47
48 class testapp(App):
49 def build(self):
50 return rootwd()
51 if __name__ == '__main__':
52 testapp().run()
Example 15.2
Let’s analyze the program given in example 15.2.
Line 8: Class rootwd belongs to the class GridLayout
class rootwd(GridLayout):
60
e
Line 12 to 14: Add labels first number, second number and result to the first Gui
Programming
row of the rootwd grid layout. Using Kivy
Libraries
self.add_widget(Label(text='First Number'))
self.add_widget(Label(text='Second Number'))
self.add_widget(Label(text='Result'))
Line 16 to 24: Add 3 text inputs named fno, sno and tno to the rootwd grid
layout. Font size of each text input is set to 30 and muti line of text inputs are
set to false. Line 17 is used to add text input to the rootwd grid layout.
self.fno = TextInput(multiline=False,font_size=30)
self.add_widget(self.fno)
#
self.sno = TextInput(multiline=False,font_size=30)
self.add_widget(self.sno)
#
self.tno = TextInput(multiline=False,font_size=30)
self.add_widget(self.tno)
self.display=self.tno
Line 26 to 28: Add button named btnadd to the grid layout and its text is “+”
and font size is set to 30. Code in the line 28 bind the on_press (when press
on the button) to the method btnaddcal.
btnadd=Button(text="+",font_size=30)
self.add_widget(btnadd)
btnadd.bind(on_press=self.btnaddcal)
Line 38 to 39: Method btnaddcal, calculates the addition of two input texts
“fno” and “sno” then result is assigned to the “tno”.
def btnaddcal(self,instance):
self.tno.text=str(float(self.fno.text)+float(self.sno.text))
Lines 41 to 48 are same type of methods used to subtract and multiply two
numbers.
61
Data Handling, Mobile
Application & Gui
Two programming code files are used for this method. Name of the first file
Development Using example 15.3(a) is twonum.py and name of the second file example 15.3(b)
Python is twonum.kv. Now consider the Python program code in twonum.py
Example 15.3 (a) twonum.py program code
1 import kivy
2 from kivy.app import App
3 from kivy.uix.gridlayout import GridLayout
4
5 class twonumgrid(GridLayout):
6 def cal(self,fnum,snum,op):
7 if op=="+":
8 self.display.text=str(float(fnum)+float(snum))
9 elif op=="-":
10 self.display.text=str(float(fnum)-float(snum))
11 elif op=="*":
12 self.display.text=str(float(fnum)*float(snum))
13
14 class twonumapp(App):
15
16 def build(self):
17 return twonumgrid()
18
19 if __name__ == '__main__':
20 twonumapp().run()
class twonumgrid(GridLayout):
def cal(self,fnum,snum,op):
if op=="+":
self.display.text=str(float(fnum)+float(snum))
elif op=="-":
self.display.text=str(float(fnum)-float(snum))
elif op=="*":
self.display.text=str(float(fnum)*float(snum))
62
Gui
e Programming
Example 15.3 (b) twonum.kv program code Using Kivy
Libraries
1 <CusButton@Button>:
2 font_size: 40
3
4 <CusText@TextInput>:
5 font_size: 35
6 multiline: False
7
8 <twonumgrid>:
9 id: twonumcal
10 display: result
11 rows: 2
12 padding: 10
13 spacing: 10
14
15 BoxLayout:
16 CusText:
17 id: fno
18 CusText:
19 id: sno
20 Label:
21 text: '='
22 font_size: 40
23 CusText:
24 id: result
25
26 BoxLayout:
27 CusButton:
28 text: "+"
29 on_press: twonumcal.cal(fno.text,sno.text,self.text)
30 CusButton:
31 text: "-"
32 on_press:twonumcal.cal(fno.text,sno.text,self.text)
33 CusButton:
34 text: "*"
35 on_press: twonumcal.cal(fno.text,sno.text,self.tex
<CusText@TextInput>:
font_size: 35
multiline: False
Line 15 to 24: Boxlayout for the first row of the gridlayout is declared in
these lines. Under the BoxLayout, there are two CusText text inputs which
are identified by fno and sno. Another label is included for “=” and another
CusText text input is included for displaying result and identified by “result”.
BoxLayout:
CusText:
id: fno
CusText:
id: sno
Label:
text: '='
font_size: 40
CusText:
id: result
Line 26 to 35: Second row of the gridlayout has another BoxLayout and it
has three (3) CusButtons. Text of each CusButton is +, - and *. Method “cal”
of the class “twonumgrid” with its paramters in the twonum.py can
be invoked by the on_press event. Input parameters are fno.text, sno.text and
text of the Relevant CusButton.
BoxLayout:
CusButton:
text: "+"
on_press: twonumcal.cal(fno.text,sno.text,self.text)
CusButton:
text: "-"
on_press: twonumcal.cal(fno.text,sno.text,self.text)
CusButton:
text: "*"
on_press: twonumcal.cal(fno.text,sno.text,self.text)
Now, let us analyse the two program codes title.py and title.kv. First, we will
analyse the codes of title.py
Example 15.4 (a) title.py
1 import kivy
2 from kivy.app import App
3 from kivy.uix.gridlayout import GridLayout
4 class titledes(GridLayout):
5 def __init__ (self, **kwargs):
6 super().__init__ (**kwargs)
7 self.tt=""
8 def disptitle(self,name,age):
9 self.display.text=self.tt+" "+name+", your age is "+age
10 def cngtt(self,x):
11 self.tt=x
12 class titleApp(App):
13 def build(self):
14 return titledes()
15 titlapp=titleApp()
16 titlapp.run()
Line 4: class “titledes” is derived from the class “GridLayout” in the kivy
library.
class titledes(GridLayout):
Line 8 to 9: Method to receive name and age form the title.kv file and they
combined with the title (self.tt). Output is self.display.text. The display is
declared in the .kv file under the class “titledes” gridlayout for the “strtxt”
Textinput widget which is the output display place.
def disptitle(self,name,age):
self.display.text=self.tt+" "+name+", your age is "+age
66
e 1 <Cuslabel@Label>:
2 font_size: 30
3 canvas.before:
4 Color:
5 rgb: 0, 1, 0
6 Rectangle:
7 pos: self.pos
8 size: self.size
9 <Custext@TextInput>:
10 font_size: 30
11 multiline: False
12 <titledes>:
13 id: titledisp
14 display: strtxt
15 canvas.before:
16 Color:
17 rgb: 1, 0, 0
18 Rectangle:
19 pos: self.pos
20 size: self.size
21 rows: 4
22 BoxLayout:
23 padding: 5
24 Cuslabel:
25 text: "Enter name"
26 size_hint_x: None
27 width: 200
28 Custext:
29 id: nametxt
30 BoxLayout:
31 padding: 5
32 Cuslabel:
33 text: "Age"
34 size_hint_x: None
35 width: 200
36 Custext:
37 id: agetxt
38 GridLayout:
39 padding: 10
40 cols: 4
41 BoxLayout:
42 width: 2
43 canvas.before:
44 Color:
45 rgb: .1, .1, 0.1
46 Rectangle:
47 pos: self.pos
48 size: self.size
49 orientation: 'vertical'
50 Cuslabel:
51 text: "Title"
52 size_hint_x: None
53 width: 200
54 CheckBox:
55 id: c1
56 group: "title"
57 on_active:
58 titledisp.cngtt(ttmr.text)
59 CheckBox:
60 id: c2
61 group: "title"
62 on_active:
63 titledisp.cngtt(ttmrs.text)
64 CheckBox:
65 id: c3
66 group: "title"
67 on_active:
68 titledisp.cngtt(ttms.text)
69 BoxLayout:
70 width: 20
67
Data Handling, Mobile
Application & Gui
71 orientation: 'vertical'
Development Using
72 Cuslabel:
Python
73 Cuslabel:
74 id: ttmr
75 text: "Mr."
76 Cuslabel:
77 id: ttmrs
78 text: "Mrs."
79 Cuslabel:
80 id: ttms
81 text: "Ms."
82 BoxLayout:
83 BoxLayout:
84 Button:
85 font_size: 30
86 text: 'Click'
87 on_press:
88 titledisp.disptitle(nametxt.text,agetxt.text)
BoxLayout:
Custext:
id: strtxt
readonly: True
Line 3 to 8: Declare Canvas, which is the root object used for drawing by a
widget. These lines are focused to change color of the relevent widget. Here,
it is “Cuslabel” Its color is green. The “rgb: 0,1,0” means red is 0, green is 1
and blue is 0.
canvas.before:
Color:
rgb: 0, 1, 0
Rectangle:
pos: self.pos
size: self.size
Line 9 to 11: “Custext” is an instance of “ TextInput” class. Its font size is set
to 30 and multiline is off.
<Custext@TextInput>:
font_size: 30
multiline: False
68
e Gui
<titledes>: Programming
id: titledisp Using Kivy
display: strtxt Libraries
canvas.before:
Color:
rgb: 1, 0, 0
Rectangle:
pos: self.pos
size: self.size
rows: 4
Line 22 to 29: BoxLayout is inserted to the first row of the GridLayout. It has
a Cuslabel to display “Enter am” and a Custext to input the name.
BoxLayout:
padding: 5
Cuslabel:
text: "Enter name"
size_hint_x: None
width: 200
Custext:
id: nametxt
Line 41 to 49: BoxLayout is inserted to the first column of the third row.
Widgets can be inserted vertically because orientation is 'vertical'. Color of
the BoxLayout also changes.
BoxLayout:
width: 2
canvas.before:
Color:
rgb: .1, .1, 0.1
Rectangle:
pos: self.pos
size: self.size
orientation: 'vertical'
69
Data Handling, Mobile
Application & Gui
Line 50 to 65: first row of the first column of the third row is allocated to
Development Using label the “Title”. Other three rows are filled with three (3) CheckBoxes.
Python Active CheckBox call the “cngtt” method of the ttle.py file with relevant text
parameter of the Label of checkbox. All the CheckBoxes are grouped as
“title”. When they are grouped, only one checkbox can be selected at a time.
Cuslabel:
text: “Title”
size_hint_x: None
width: 200
CheckBox:
id: c1
group: “title”
on_active: titledisp.cngtt(ttmr.text)
CheckBox:
id: c2
group: “title”
on_active: titledisp.cngtt(ttmrs.text)
CheckBox:
id: c3
group: “title”
on_active: titledisp.cngtt(ttms.text)
Line 79 to 84: Empty BoxLayout is inserted to the third column of the third
row. Then BoxLayout is inserted to fourth column of the third row for
inserting the Button for “Click”. When the Button is pressed, method
“disptitle” will call with 2 parameters “nametxt.text” and “agetxt.text”.
BoxLayout:
BoxLayout:
Button:
font_size: 30
text: 'Click'
on_press: titledisp.disptitle(nametxt.text,agetxt.text)
Activity15.1
Write a GUI program using kivy libraries and kv language to input 2 boolean
values (0 or 1) and select a boolean operation from set of boolean operations
AND, OR, NAND, NOR, XOR. Result should be printed in a text box next to
the boolean selection box.
Q-3 Discuss various methods for coding the mobile GUI applications.
15.9 SUMMARY
In this unit you learned how to create a graphical user interface with kivy
libraries using only Python as well as using both Python and Kv language.
We also discussed calling methods in Python on actions of Kivy widgets.
71
Data Handling, Mobile
Application & Gui
Development Using
Appendix 1 Answers to Activities given in
Python Python book
Unit 01
Activity1.1
1) Python is a programming language which has a very simple and
consistent syntax. It allows beginners to concentrate on important
programming skills. Python helps to introduce basic concepts such as
loops and procedures quickly to students.
2) There is an interactive interpreter in Python which helps students to test
language features while they’re programming. Students would be able to
see both windows (the interpreter running and their program’s source) at
the same time.
3) Good IDEs are available for Python.
4) Python language is intuitive and fun. Since Python is an open source
programming language, it reduced up-front project costs as well.
Activity1.2
Nowadays, Python is used in many application domains to cater for Web and
Internet Development, Scientific and Numeric applications, Education
applications, Desktop GUIs and Software Development.
Activity1.3
See HELP documents if you cannot get the PATH setup correctly. Issues
vary depending on the directory you installed Python and the operating
system.
UNIT 02
Activity2.1
Typing each statement will give you following results.
>>> 55
55
>>> x=55
>>> x+1
56
In a new file from IDE type; 55
x = 55
print(x) x + 1 print(x)
Save the file and select ‘run module’ from Run. Output was;
====== RESTART: C:/Users/sarala/Documents/COL/Check Your
Progress2- printscript1.py ======
72
e 55
55
>>>
Activity 2.2
>>> width = 42
>>> height = 14
>>> width/3 14.0
>>> width/3.0 14.0
>>> height/3 4.6666666666666665
>>> 13 + 25* 10
263
Activity 2.3
1. >>>h
=6
>>>r =
2
>>> pi = 3.141592
>>> volume= pi*r*r*h
>>>print(volume)
UNIT 03
Activity3.1 #Program to print even numbers between 20 and 60
n = 20
while n <= 60 :
n=n+2
print(n)
print('All even numbers between 20 to 60 are printed')
Activity3.2
# Use of For loop
import math
numberlist = [1,2,3,4,5]
for no in numberlist:
print(no, "cube of ", no, " is", (math.pow(no,3)))
Activity3.3
>>> car = ('Toyota', 'Aqua', 2015, 'TA-181')
>>> print(car)
('Toyota', 'Aqua', 2015, 'TA-181')
UNIT 04
Activity4.1
def findPrime(no):
i = 0 divisorList=[2,3,5,7,11,13,17,19]
for j in divisorList: 73
Data Handling, Mobile if (no != j)and (no % j == 0)
Application & Gui
Development Using : i =1
Python
if i == 1:
print("False")
else:
print ("True") findPrime(4)
findPrime(1)
findPrime(19)
Required argument type is used
Activity4.2
no = 397.234567
print(round(no,3))
397.235
Activity4.3
>>> g = lambda x : x**2
81
UNIT 05
Activity5.1
flower = "jasmine" index = len(flower)- 1
while index >= 0:
letter = flower[index] print (letter)
index = index - 1
Activity5.2
>>>
flow
er[:]
'jas
min
e'
Activity5.3
(i)
str1 = 'Divya asked, '
str2 = 'Great! Then can you let me have all the mangos, limes,
oranges and apples?'
str3 =str1 + str2 print(str3) index = 0
while index < len(str3):
74
e letter = str3[index]
if letter.isalpha():
print (letter)
else:
print(' ')
index = index + 1
(ii)
str1 = 'Divya asked, '
str2 = 'Great! Then can you let me have all the mangos, limes, oranges and apples?'
str3 =str1 + str2 print(str3) index = 0
while index < len(str3):
letter = str3[index]
if letter.isalpha():
print (letter, end =" ")
else:
print(' ', end =" ")
index = index + 1
UNIT 06
Activity6.1:
Write a Student class which contains studentID, lastName, courseID.
Input values to one object of type student and print the values.
class Student:
>>>s1 = Student();
>>>print(s1.studentID, s1.lastName, s1.courseID)
Activity6.2:
Write an init method for the Bikeclass that takes gear and speed
and initialize them.
# inside class Bike:
Activity6.3:
Write a __str__ method for the Bike class and print it.
.# inside class Bike:
Def __ str__ (self)
Return(‘Gear %d%, speed ’%(self.gear, self.speed))
>>> myBike = Bike(2,35)
>>> print(myBike)
UNIT 07
Activity7.1:
1) Write a Person Class. Make another class called Student and inherits it
from Person class. 75
Data Handling, Mobile
Application & Gui
2) Define few attributes that only have with Student class, such as school
Development Using they are associated with, graduation year, GPA etc.
Python
3) Create an object called student
Set some attribute values for the student, that are only coded in the Person
class and another set of attribute values for the student, that are only in
the Student class.
4) Print the values for all of these attributes.
Activity7.2:
A CEO buys a car. Later on the CEO buys two new cars BMW and a
Mercedez. There is a driver for the CEO who chooses a car to drive to the
office.
1) Identify the classes involved in this scenario.
2) Select appropriate superclass and subclasses
3) Implement move method inside the superclass.
4) Invoke the move method in superclass by creating instances of subclasses
from a sub class.
5) Implement the move method inside the subclasses.
6) Override the move methods by creating instances of sub class.
class Person:
def __init__(self, name, surname, idno):
self.name = name
self.surname = surname
self.idno = idno
class CEO(Person):
def __init__(self, xxx, *args, **kwargs):
self.xxx = xxx
super(CEO, self).__init__(*args, **kwargs)
class driver(Person):
PERMANENT, TEMPORARY = range(2)
def __init__(self, employment_type, *args, **kwargs):
self.branch = []
self.employment_type = employment_type
super(driver, self).__init__(*args, **kwargs)
def enrol(self, yyy):
self.branch.append(yyy)
class vehicle:
def __init__(self, model, make,color, gear, *args, **kwargs):
self.model = model
self.make = make
self.idno = color
self.gear = gear
class car(vehicle):
76 def __init__(self, currFuel, miles, *args, **kwargs):
e self.currFuel = currFuel
self.miles = miles
super(car, self).__init__(*args, **kwargs)
def move(self, miles):
fuelNeeded = miles/10
if self.currFuel <= fuelNeeded:
print("Need re-fueling")
else:
print("Has sufficient fuel, can move")
return {"changeSpeed", self.gear}
BMW=car(23,34, 'x','xx','brown', 2)
BMW.move(34)
UNIT 08
Activity8.1:
List the different types of errors and explain how you can identify them
separately.
Syntax errors are produced by Python when it is translating the source code
into byte code. They usually indicate that there is something wrong with the
syntax of the program.
Runtime errors are produced by the interpreter if something goes wrong
while the program is running. Most runtime error messages include
information about where the error occurred and what functions were
executing.
Semantic errors are problems with a program that runs without producing
error messages but doesn’t do the right thing. In other words the program
does execute the correct logic.
Activity8.2:
What are exceptions and why is it important to handle them appropriately.
State with examples.
Errors detected during execution are called exceptions and are not
unconditionally fatal.
Essentially, exceptions are events that modify program’s flow, either
intentionally or due to errors. They are special events that can occur due to an
error, e.g. trying to open a file that doesn’t exist, or when the program
reaches a marker, such as the completion of a loop.
Example: When something goes wrong during the runtime, Python prints a
message that includes the name of the exception, the line of the program
where the problem occurred, and a traceback.
Activity8.3:
Describe what user-defined exceptions are.
77
Data Handling, Mobile
Application & Gui
These are exceptions that Python allows the programmer to create based on
Development Using his/her requirements. However it is better to check before creating an
Python exception if there is already an existing one.
UNIT 09
Activity9.1:
Explain the difference between white box testing and black box testing.
White Box testing is where the internal structure of the system such as
control structures of the program are tested and the Black Box testing is
where the functionalities of the system is tested without going into the details
of the implementation.
Activity9.2:
Test suite: A test suite is a collection of test cases, test suites, or both. It is
used to aggregate tests that should be executed together.
Explain the concepts used in unit testing.
unittest supports test automation, sharing of setup and shutdown code for
tests, aggregation of tests into collections, and independence of the tests from
the reporting framework. A few of the concepts that is supported by Python
includes:
Test fixture: A test fixture represents the preparation needed to perform one
or more tests, and any associate cleanup actions.
Test case: A test case is the smallest unit of testing. It checks for a specific
response to a particular set of inputs.
Activity9.3:
Write a test case for a string method that test for a “FOOD”.
Please refer to the unit testing video.
UNIT 10
Activity10.1:
What is a debugger framework (bdb) and state each functions it handles with
examples.
The bdp module handles basic debugger functions, like setting breakpoints or
managing execution via the debugger.
The following syntax is used to define the exception which would be raised
by the bdb class for quitting the debugger.
exception bdb.BdbQuit
Activity10.2:
78
e
What is a Python debugger (pdb) and what are the debugging functionalities
it supports.
The module pdb defines an interactive source code debugger for Python
programs. It supports setting (conditional) breakpoints and single stepping at
the source line level, inspection of stack frames, source code listing, and
evaluation of arbitrary Python code in the context of any stack frame. It also
supports post-mortem debugging and can be called under program control.
Activity10.3:
What is a profile and by referring to the examples above(in the text book),
profile a function that takes in a single argument.
It provides a very brief overview, and allows a user to rapidly perform
profiling on an existing application.
To profile a function that takes a single argument, you can do:
import cProfile
import re
cProfile.run('re.compile("foo|bar")')
UNIT 11
Activity11.1:
Have to write the database as instructed
UNIT 12
Activity12.1:
You need to research on the internet to find out the most popular Python
libraries or packages available as open source repositories to use in different
domains such as data science, image processing, information retrieval, data
manipulation etc. Few such libraries are given below.
SQLAlchemy: This is used as the Python SQL toolkit and Object Relational
Mapper.
Pillow : This is a Python Imaging Library(PIL) which adds image processing
capabilities to the Python interpreter.
Scrapy : A collaborative framework for extracting the data required from
websites.
NumPy: This is the fundamental package for scientific computing with
Python.
Matplotlib: This is a Python 2D plotting library which produces quality
figures.
UNIT 13
Activity13.1:
79
Data Handling, Mobile
Application & Gui
The Kivy launcher can be used to run the Kivy applications on Android
Development Using devices without compiling them. Kivy launcher runs your Kivy application
Python when you copy it inside the SD Card of your device.
To install the Kivy launcher, you must go to the Kivy Launcher page on the
Google Play Store. Then click on Install and select your phone. If not you can
go to https://kivy.org/#download and install the APK manually.
Once the Kivy launcher is installed, you can put your Kivy applications in the
Kivy directory in your external storage directory. Often the application is
available at /sdcard even in devices where this memory is internal. For an
example /sdcard/kivy/<your application>
def oncombo(self,event):
self.lsel = self.combo.GetValue()
if self.lsel=="AND":
if self.n0.GetValue()=="1" and self.n1.GetValue()=="1":
self.result.SetValue("1")
else:
self.result.SetValue("0")
app = wx.App()
top=logicex("Logic Example")
top.Show()
app.MainLoop()
UNIT 15
Assignment 15.1: Answer
andk.py file
import kivy
andk.kv file from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
class andkgrid(GridLayout):
def callog(self,n0,n1,lg):
if lg=="AND":
if n0=="1" and n1=="1":
self.display.text=str(1)
else:
self.display.text=str(0)
class andkapp(App):
def build(self):
return andkgrid()
if __name__ == '__main__':
andkapp().run()
81
Data Handling, Mobile * <CusButton@Button>:
Application & Gui font_size: 40
Development Using <CusText@TextInput>:
Python font_size: 35
multiline: False
<andkgrid>:
id: andkcal
display:result
rows:3
padding: 10
spacing: 10
BoxLayout:
CusText:
id: q0
Label:
text: ''
font_size: 40
Label:
text: ''
font_size: 40
BoxLayout:
spacing: 10
Label:
text: ''
font_size: 40
CusButton:
text: "AND"
on_press: andkcal.callog
(q0.text,q1.text,self.text)
CusText:
id: result
BoxLayout:
spacing: 10
CusText:
id: q1
Label:
text: ''
font_size: 40
Label:
text: ''
font_size: 40
82