Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
374 views

Ebook Python GUI Programming With Tkinter

Python programme project
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
374 views

Ebook Python GUI Programming With Tkinter

Python programme project
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/371730724

Python GUI Programming with Tkinter

Book · September 2021

CITATIONS READS

0 56

1 author:

Mastura Ramli
Politeknik Sultan Mizan Zainal Abidin
18 PUBLICATIONS 5 CITATIONS

SEE PROFILE

All content following this page was uploaded by Mastura Ramli on 21 June 2023.

The user has requested enhancement of the downloaded file.


PHYTON

GUI Programming
with Tkinter

Penulis:
Siti Zaharah Binti Sidek
Mastura Binti Ramli
Siti Norhidayah Binti Saad

Teknologi & Perkomputeran


Page |i

PHYTON – GUI Programming with Tkinter

Siti Zaharah binti Sidek | Mastura binti Ramli | Siti Norhidayah binti Saad
P a g e | ii

Preface

This book explains what the Python-GUI is and how to connect Python with database using
SQLite and MySQL. It also covers the step of installing SQLite, MySQL connector and Tkinter.
There are several tutorials available to learn SQLite and MySQL command and how to
create GUI using Tkinter and connect with database by using MySQL. It also includes
interactive quizzes and puzzles for more interesting learning.
P a g e | iii

Python- GUI PROGRAMMING WITH TKINTER

Editor
Atijah binti Marsithi

Writer
Siti Zaharah binti Sidek
Mastura binti Ramli
Siti Norhidayah binti Saad

Issued in 2021

All rights reserved. No part of this book maybe reproduced in any form on by an electronic or
mechanical means, including information storage and retrieval systems, without permission
in writing from the publisher, except by a reviewer who may quote brief passengers in a
review.

E-ISBN 978-967-2498-31-5

Published By

Politeknik Muadzam Shah


Lebuhraya Tun Abdul Razak
26700 Muadzam Shah
Pahang Darul Makmur.
Tel : 09-450 2005/2006/2007
Fax : 09-450 2009
P a g e | iv

TABLE OF CONTENT

PREFACE ........................................................................................................................................ II
TABLE OF CONTENT ...................................................................................................................... IV
CHAPTER 1 ‐ PYTHON GUI PROGRAMMING.....................................................................................1
1.1 Introduction to Graphical User Interface (GUI) ................................................................... 1
1.2 GUI Programming ................................................................................................................ 2
1.3 Python GUI Programming with Tkinter ............................................................................... 2
CHAPTER 2 ‐ TKINTER ......................................................................................................................5
2.1 What is Tkinter used for? ..................................................................................................... 5
2.2 Tkinter Installation in Windows........................................................................................... 5
2.3 Layout Management ............................................................................................................ 6
2.4 Widgets in Tkinter ................................................................................................................ 8
CHAPTER 3 ‐ DATABASE IN PYTHON .............................................................................................. 11
3.1 Introduction to Database ................................................................................................... 11
3.2 SQLite .................................................................................................................................. 12
3.3 MySQL ................................................................................................................................. 17
TUTORIAL .....................................................................................................................................23
1.1 ‐ CREATE PYTHON DATABASE USING SQLITE ......................................................................................... 23
1.2 ‐ CREATE PYTHON DATABASE USING MYSQL ........................................................................................ 29
1.3 ‐ CREATE GUI BY ADDING WIDGETS AND MANAGING LAYOUT................................................................. 37
1.4 ‐ ADD EVENT HANDLING INTO GUI ..................................................................................................... 39
DO‐IT‐YOURSELF ........................................................................................................................... 43
1 ‐ CREATE COMMAND LINE INTERFACE APPLICATION (CLI) BASED ON CRUDS APPLICATION ......... 43
2 ‐ CREATE APPLICATION FORM USING TKINTER WIDGETS AND DATABASE INTEGRATION ............. 46
REFFERENCES ................................................................................................................................51
PHYTON
GUI PROGRAMMING WITH
TKINTER

SITI ZAHARAH BINTI SIDEK


MASTURA BINTI RAMLI
SITI NORHIDAYAH BINTI SAAD
Page |v

CHAPTER 1
Page |1

CHAPTER 1 - PYTHON GUI PROGRAMMING

1.1 Introduction to Graphical User Interface (GUI)

A GUI (graphical user interface) is a system of interactive visual components


for computer software system. A GUI presents objects that convey information and
represent actions that can be carried by the user. The objects change color, size, or
visibility when the use r interacts with them.
The GUI was first developed at Xerox PARC by Alan Kay, Douglas Engelbart, and
a group of other researchers in 1981. Later, Apple introduced the Lisa computer with
a GUI on January 19, 1983.
How do you pronounce GUI? GUI is most often pronounced by saying each
letter (G-U-I or gee-you-eye). It sometimes is also pronounced as "gooey."

Picture from https://whatvwant.com/embedded-gui/

GUI can be categorized into 3 types. The types of GUI is as the following.
a. GUI – Graphical User Interface
b. CLI – Command Line Interface
c. TUI – Terminal User Interface
Page |2

1.2 GUI Programming

A GUI program has the subsequent structure:


i. Create the icons and widgets that are displayed to a user and arrange them
inside a screen window.
ii. Define functions that will process user and application events.
iii. Associate specific user events with specific functions.
iv. Start an infinite event-loop that processes user events. When a user event
happens, the event-loop calls the function associated with that event.
A GUI program’s interface is composed of widgets displayed in a window. Your
computer’s operating system controls the creation and manipulation of windows on
your computer’s display screen. The operating system also controls the pointing
devices on your computer, such as a mouse or a touch screen. Therefore, your
computer’s operating system is what recognizes events that happen in a window. Your
operating system sends events to your program in the order they are generated by a
user. Your program’s event-loop responds to these events.

1.3 Python GUI Programming with Tkinter

Tkinter is a GUI (graphical user interface) widget set for Python. Python has a
lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python
standard library. Tkinter has several strengths. It’s cross-platform, so the same code
works on Windows, macOS, and Linux. Visual elements are rendered using native
operating system elements, so applications built with Tkinter look like they belong on
the platform where they’re run.

Although Tkinter is considered the de-facto Python GUI framework, it’s not
without criticism. One notable criticism is that GUIs built with Tkinter look outdated.
If you want a shiny, modern interface, then Tkinter may not be what you’re looking
for.

However, Tkinter is lightweight and relatively painless to use compared to


other frameworks. This makes it a compelling choice for building GUI applications in
Python, especially for applications where a modern sheen is unnecessary, and the top
priority is to build something that’s functional and cross-platform quickly.
Page |3

Picture from https://realpython.com/python-gui-tkinter/


Page |4

CHAPTER 2
Page |5

CHAPTER 2 - TKINTER

2.1 What is Tkinter used for?

Now, let's build a very simple GUI with the help of Tkinter and understand it
with the help of a flow diagram for rendering a Basic GUI.

Picture from https://www.datacamp.com/community/tutorials/gui-tkinter-python

2.2 Tkinter Installation in Windows

To install Tkinter, we need Python pre-installed. Tkinter comes along when


we install Python. While installing Python, we need to check the td/tk and IDLE
checkbox. This will install the tkinter and we need not install it separately.
Page |6

However, if we missed installing Tkinter while installing Python, we can do it


later use the pip command.

2.3 Layout Management

Tkinter is the most popular way to create Graphical User Interfaces (GUIs) in
Python. For building GUIs, Tkinter provides developers with a few standard widgets,
including buttons, labels, and text boxes.
Each of these widgets need to be positioned for user accessibility and widget
focus, and then programmed with underlying application logic so they can work as
intended in response to mouse clicks and other actions.
Tkinter has three built-in layout managers that use geometric methods to
position widgets in an application frame. According to (David, 2018) Widgets are
placed into their parents using special functions called geometry managers. There are
three geometry managers available in Tkinter – pack, grid, and place.
Page |7

Picture from
http://gatherworkshops.github.io/programming/courses/tkinter/layouts.html

The description of layout management for every types is based on the Table
2.1 below.
Table 2.1: Layout Management Description

Geometry managers Description


method

pack () Organizes widgets in horizontal and vertical boxes that


are limited to left, right, top, bottom positions. Each box
is offset and relative to each other.

grid () Locates widgets in a two-dimensional grid using row


and column absolute coordinates.

place () Places widgets in a two-dimensional grid using x and y


absolute coordinates.

Important:
pack (), place (), and grid () should not be combined in the same master window.
Instead choose one and stick with it.
Page |8

2.4 Widgets in Tkinter

Tkinter is the most popular way to create Graphical User Interfaces (GUIs) in
Python. For building GUIs, Tkinter provides developers with a set of widgets.
In general, Widget is an element of Graphical User Interface (GUI) that
displays/illustrates information or gives a way for the user to interact with the OS. In
Tkinter, Widgets are objects; instances of classes that represent buttons, frames, and
so on.
The Tk widget exposes various window properties, such as the text within the
top bar of the application, the size of the application, its position on screen, whether
it can be resized, and even the icon which appears in the top right-hand corner (on
Windows only) (David, 2018).
Each separate widget is a Python object. When creating a widget, you must
pass its parent as a parameter to the widget creation function. The only exception is
the “root” window, which is the top-level window that will contain everything else,
and it does not have a parent. The list of python widgets is based on the Table 2.2
below.

Table 2.2: Python Widgets

Widget Description
Label Display text or messages
Button Used in toolbars, application windows, pop-up windows, and
dialogue boxes
Checkbutton Used to implement on-off selections.
Entry Widget Used to enter or display a single line of text
Scale widget Used instead of an Entry widget when you want the user to
input a bounded numerical value.
List box Used to display a list of alternatives.
Radiobutton Used to offer many possible selections to the user but lets the
(alternate) user choose only one of them.
Text Widget Used where a user wants to insert multiline text fields.
Canvas Rectangular area intended for drawing pictures or other
complex layouts. You can place graphics, text, widgets, or
frames on a Canvas.
LabelFrame A simple container widget and act as a spacer or container for
complex window layout.
Page |9

Menu Used to create various types of menus (top level, pull down, and
pop up) in the python application.
OptionMenu Which implements a special type that generates a pop-up list of
items within a selection.
P a g e | 10

CHAPTER 3
P a g e | 11

CHAPTER 3 - DATABASE IN PYTHON

3.1 Introduction to Database

A database is a set of related data that has a regular structure and organized
in such a way typically stored electronically in a computer system. A database is usually
controlled by a database management system (DBMS). The DBMS allows data storage,
retrieval, privacy, security and integrity. There are many commercial and open source
database as the following:
a) Commercial (SQL Server, Oracle, Ms Access)
b) Open Source (MySQL, SQLite)
Like others programming language, Python also has features for database
programming. In python, we have to first establish a connection between python file
and the database. After that, we can add, search, delete or update the database.
Moreover, we can retrieve the data from the database, make any operation on it then
re-add it to the database. The database operations are performed using the SQL
language as shown in the Figure 3.1 below. Data is either in memory, files or
databases. Python supports various databases like SQLite, MySQL, Oracle, Maria DB,
PostgreSQL, etc. Python also supports Data Definition Language (DDL), Data
Manipulation Language (DML) and Data Query Statements.

Figure 3.1: Illustration Python Connection with Database


In this chapter, we will explain about SQLite and MySQL integration with
Python programming code.
P a g e | 12

3.2 SQLite

SQLite is an Open Source Database. SQLite supports standard relational


database features like SQL syntax, transactions and prepared statements. In addition,
it requires only little memory at runtime (approx. 250 Kbyte).
SQLite implements a self-contained, server-less, zero-configuration and
transactional SQL database engine. SQLite is the most widely deployed SQL database
engine in the world.

3.2.1 SQLite Features


a) Self-contained
SQLite is self-contained means it requires minimal support from the operating
system or external library. This makes SQLite usable in any environment especially in
embedded devices like iPhones, Android phones, game consoles, handheld media
players, etc.
SQLite is developed using single ANSI-C. It is easy to compile and easy to add
into a larger project. If we want to develop an application that uses SQLite, we just
need to drop sqlite3.c and sqlite3.h files into our project and compile it with our code.

b) Server-less
Normally, DBMS such as MySQL, PostgreSQL, etc., requires a separate server
process to operate. This is called client-server architecture. The following diagram
illustrates the DBMS client-server architecture:

Figure 3.2: DBMS client-server architecture


P a g e | 13

But, SQLite does not work this way and did not used server to operate. SQLite
database is integrated with the application that accesses the database. The
applications interact with the SQLite database read and write directly from the
database files stored on disk. The following diagram illustrates the SQLite server-less
architecture:

Figure 3.3: SQLite server-less architecture

c) Zero-configuration
We don’t need to install SQLite before using it. There is no server process that needs
to be configured, started, and stopped the server. SQLite also does not use any
configuration files.

d) Transactional
All transactions in SQLite are fully ACID-compliant. It means all queries and changes
are Atomic, Consistent, Isolated, and Durable. In other words, all changes within a
transaction take place completely or not at all even when an unexpected situation like
application crash, power failure, or operating system crash occurs.

3.2.2 SQLite Data Types


The data type of a value in SQLite is associated with the value itself, not with its
container. Every value which is stored in a SQLite database has one of storage classes
based on the Table 3.1 below.
P a g e | 14

Table 3.1: SQLite Storage Classes

Storage Classes Description


NULL Store a null value
INTEGER Store a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes
depending on the magnitude of the value
REAL Storing floating point value
TEXT Storing text or strings
BLOB The value is a blob of data, stored exactly as it was input.

3.2.3 SQLite Management Tools


SQLite Expert is a Free GUI-based management tool for SQLite databases. With this
application we can easily manage the database that we have created. The interface of
SQLite Expert is as shown in Figure 3.4 below.

Figure 3.4: SQLite Expert Interface

We can download it for free. To download SQLite Expert application just go to URL
below.

https://sqlite-expert-personal.software.informer.com/download/
P a g e | 15

3.2.4 SQLite Installation

SQLite3 can be integrated with Python using sqlite3 module. The module is no need
to install separately because it is imported by default along with Python version 2.5.x
onwards. To use sqlite3 module, firstly must create a connection object that
represents the database and then optionally create a cursor object, which will help in
executing all the SQL statements.

3.2.5 SQLite Syntax

a) Import sqlite3 module into python program.

b) Create sqlite3 database using connect () function and specifying a file name. If
the database does not exist, then it will be created and finally a database object
will be returned.

c) SQL command can be executed by calling execute () function.

d) The commit () function needs to be called if there is a modification (insert,


create, drop, delete and update) on the database for the command to take
effect.
P a g e | 16

e) When executing a SQL select command, the execute () function return a cursor
which can be iterated over with a for loop to access the records returned.

3.2.6 SQLite Commands


The standard SQLite commands are similar to SQL when to interact with relational
databases. The SQLite commands are based on the Table 3.2 below.

Table 3.2: SQLite Commands


No. Commands & Description
1 CREATE
Creates a new table, a view of a table, or other object in database.
2 ALTER
Modifies an existing database object, such as a table.
3 DROP
Deletes an entire table, a view of a table or other object in the database.
4 INSERT
Create a new record and insert into table.
5 UPDATE
Update record if there is any modification on the record.
6 DELETE
Delete record in the table.
7 SELECT
Retrieves certain records from one or more tables.
P a g e | 17

3.3 MySQL

MySQL is one of the most popular database management systems (DBMSs) on the
market today. As most software applications need to interact with data in some form,
programming languages like Python provide tools for storing and accessing these data
sources.

To connect Python with the MySQL database we need to install the MySQL
connector. MySQL Connector enables Python programs to access MySQL databases,
using an API that is compliant with the Python Database API Specification v2.0 (PEP 249).
It is written in pure Python and does not have any dependencies except for the Python
Standard Library.

3.3.1 MySQL Installation


MySQL should be installed on our computer before we connect a database to
Python file. MySQL is a server-based database management system. One server might
contain multiple databases. To interact with a database, we must first establish a
connection with the server. The general workflow of a Python program that interacts
with a MySQL database is as follows:
a) Connect Python file to the MySQL server.
b) Create a new database.
c) Connect to the newly created or an existing database.
d) Execute a SQL query and fetch results.
e) Inform the database if any changes are made to a table.
f) Close the connection to the MySQL server.
This is the most basic work process depending on the application being developed.
However, no matter what application is generated, the first step is to make a database
connection to our application.

3.3.2 Step to Install MySQL Connector in Python


1. Install MySQL Workbench to create a database on our localhost. Download a free
MySQL database at http://dev.mysql.com/downloads/workbench/.
P a g e | 18

2. Open Command Prompt to check your python version (based on which version you
install) and type the command to check the version.
a. python –version (to check python version)
b. pip –version (to check standard package manager of python)

3. To install MySQL connector, the command is:


pip3 install mysql-connector

For Python 2.7 or lower install using pip as:


pip install mysql-connector

For Python 3 or higher version install using pip3 as:


pip3 install mysql-connector

4. If you get warning and asking for upgrade the pip version. You should try to upgrade
it with this command:
pip install --upgrade pip
P a g e | 19

3.3.3 MySQL Syntax


1) Import MySQL connector module into Python program.

2) Use the connect () method of the MySQL Connector class with the required
arguments to connect MySQL. It would return a MySQL Connection object if the
connection established successfully. The argument required to connect MySQL
and Python is based on the Table 3.3.

Table 3.3: MySQL Server Arguments

Argument Description
Username The username that you use to work with MySQL Server.
The default username for the MySQL database is a root.
Password Password is given by the user at the time of installing the
MySQL server. If you are using root either you won’t need
the password or you can create a password.
Host name The server name or IP address on which MySQL is running.
If you are running on localhost, then you can use localhost
or its IP 127.0.0.0.
Database name The name of the database to which you want to connect
and perform the operations.

3) Use the cursor () method of a MySQL Connection object to create a cursor object
to perform various SQL operations.
P a g e | 20

4) Use the execute () methods to run the SQL query and return the result.

5) Use fetchall () method or fetchone () method or fetchmany () method to extract


query result.
a. fetchall () to retrieve ALL data;
b. fetachmany (10) to fetch 10 data;
c. fetchone () to retrieve the first data only.

6) Use commit () method to save the data. This method is usually called when
inserting data, updating data, and deleting data.

7) Use close () method to close cursor and open connections after our work
completes.
P a g e | 21

Figure 3.5 below is the illustration of MySQL database connection in


Python. It shows how Python Application connect to MySQL database by using
MySQL connector.

Figure 3.5: MySQL Database Connection in Python


Picture from https://pynative.com/
P a g e | 22

TUTORIAL
P a g e | 23

TUTORIAL
1.1 - Create Python database using SQLite

1. CREATE Database using SQLite3 Module

i. Open your Python IDLE Shell.


ii. Click File -> New File or Click Ctrl + N

iii. Then, type the code as the following.

iv. Save the file as myDB.py.


v. Click Run  Run Module to compile the code.

vi. Open IDLE Shell and it will show as the following when the database is
successfully created.
P a g e | 24

2. CREATE Table

i. Add the following code to the current source code.

ii. Save the file.


iii. Click Run  Run Module to compile the code.
iv. Open IDLE Shell and it will show as the following when the table is
successfully created.
P a g e | 25

3. INSERT Operation

i. Add the following code to the current source code.

ii. Save the file.


iii. Click Run  Run Module to compile the code.
iv. Open IDLE Shell and it will show as the following when the record is
successfully inserted.
P a g e | 26

4. SELECT Operation

i. Add the following code to the current source code.

ii. Save the file.


iii. Click Run  Run Module to compile the code.
iv. Open IDLE Shell and it will show as the following when the record is
successfully displayed.
P a g e | 27

5. UPDATE Operation

i. Add the following code to the current source code.

ii. Save the file.


iii. Click Run  Run Module to compile the code.
iv. Open IDLE Shell and it will show as the following when the record is
successfully updated.
P a g e | 28

6. DELETE Operation

i. Add the following code to the current source code.

ii. Save the file.


iii. Click Run  Run Module to compile the code.
iv. Open IDLE Shell and it will show as the following when the record is
successfully deleted.
P a g e | 29

TUTORIAL 1.2
1.2 - Create Python database using MySQL

1. Connect Python to MySQL using MySQL Connector

i. Open MySQL Workbench and click on the red circled.

ii. Click Database tab and choose Manage Connection.

iii. Setting the server based on your own setting for username and password.
Basically, the username is root.
P a g e | 30

iv. Open your Python IDLE Shell.


v. Click File -> New File or Click Ctrl + N

vi. Then, type the code as the following.

Make sure your


username and
password are based
on your MySQL server
setting.

vii. Save the file as dbconnector.py.


viii. Click Run  Run Module to compile the code.
P a g e | 31

ix. Open IDLE Shell and it will show as the following when the database is
successfully connected.

2. CREATE Database

i. Create a new file named create_db.py. Then fill it with the following code:

ii. Save the file.


iii. Click Run  Run Module to compile the code.
P a g e | 32

iv. Open IDLE Shell and it will show as the following when the database is
successfully created.

3. CREATE Tables

i. How to create a table is the same as how to create a database. We just enter
the SQL command or query into the method execute ().
ii. But before that, make sure the connector has been given parameters
database to determine which database to use.

iii. In the code above we pass the parameter database="grocery_shop".


iv. Create a new file named create_table.py, then fill it with the following code.
P a g e | 33

v. Save the file.


vi. Click Run  Run Module to compile the code.
vii. Open IDLE Shell and it will show as the following when the table is
successfully created.

viii. Open MySQL Workbench to check your table is successful created or not. If
successful it will appear on the MySQL Workbench as the following.
P a g e | 34

4. INSERT Operation

i. Create a new file named insert_data.py, then fill it with the following code.

ii. Then, we also must include mydb.commit () to save the data. This method is
usually called when inserting data, updating data, and deleting data.
iii. Save the file.
iv. Click Run  Run Module to compile the code.
v. Open IDLE Shell and it will show as the following when the data is successfully
added.

vi. We can add multiple data at one time by do a looping based on the following
code.
P a g e | 35

5. SELECT Operation

i. Create a new file named select.py, then fill it with the following code:

ii. Save the file.


iii. Click Run  Run Module to compile the code.
iv. Open IDLE Shell and it will show all the data in database as the following.

v. Now, try it yourself to use fetchone() and fetchmany() method to display data
in databases.

6. UPDATE Operation

i. Create a new file named update.py. Then fill it with the following code:

i. In the code above, we assign a new value to the data with customer_id = 1.
Save the file.
ii. Click Run  Run Module to compile the code.
P a g e | 36

iii. Open IDLE Shell and it will show as the following when data is successfully
updated.

iv. Open your MySQL Workbench and see the changes. It will show as the
following.

7. DELETE Operation

i. Delete data the same as updating data. Use the query DELETE to delete and
WHERE to determine the data to be deleted.
ii. Create a new file named delete.py, then fill it with the following code:

iii. In the code above, data with customer_id = 1 will be deleted.


P a g e | 37

TUTORIAL 1.3
1.3 - Create GUI by adding Widgets and Managing Layout

Step 1:
In this example, we’ll use the grid geometry manager to design a login screen as follows:

Step 2:
The login screen uses a grid that has two columns and three rows. Also, the second column
is three times as wide as the first column.
P a g e | 38

Step 3:

Write the code as shown below.

import tkinter as tk
from tkinter import ttk

# root window
root = tk.Tk()
root.geometry("240x100")
root.title('Login Form')
root.resizable(0, 0)

# configure the grid


root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=3)
# password
password_label = ttk.Label(root, text="Password:")
password_label.grid(column=0, row=1, sticky=tk.W, padx=4, pady=4)

password_entry = ttk.Entry(root, show="*")


password_entry.grid(column=1, row=1, sticky=tk.E, padx=4, pady=4)
# username
username_label = ttk.Label(root, text="Username:")
username_label.grid(column=0, row=0, sticky=tk.W, padx=4, pady=4)

username_entry = ttk.Entry(root)
username_entry.grid(column=1, row=0, sticky=tk.E, padx=4, pady=4)

# login button
login_button = ttk.Button(root, text="Login")
login_button.grid(column=1, row=3, sticky=tk.E, padx=4, pady=4)

root.mainloop()
P a g e | 39

TUTORIAL 1.4
1.4 - Add Event Handling into GUI

Step 1:
In this example, we’ll create a simple calculator application as shown in Figure 1.4.1 below.

Step 2:
The application will contain 4 labels, 3 entry widget and 4 buttons.

Figure 1.4.1

Step 3:

Each of button created will embed with appropriate function to handle event handling
assigned to them. There will be add method, subtraction method, multiply method and
division method.
P a g e | 40

Step 4:
Write the code as shown below.
import tkinter as tk

root= tk.Tk()

canvas = tk.Canvas(root, width = 300, height = 280)


canvas.pack()

entry1 = tk.Entry (root)


canvas.create_window(210, 100, window=entry1)

entry2 = tk.Entry (root)


canvas.create_window(210, 140, window=entry2)

entry3 = tk.Entry (root)


canvas.create_window(210, 240, window=entry3)

labelTitle = tk.Label(root, text='Simple Calculator')


labelTitle.config(font= ('Georgia', 14))
canvas.create_window(150, 40, window=labelTitle)

labelNum1 = tk.Label(root, text='Insert Number 1:')


labelNum1.config(font= ('helvetica', 10))
canvas.create_window(100, 100, window=labelNum1)

labelNum2 = tk.Label(root, text='Insert Number 2:')


labelNum2.config(font= ('helvetica', 10))
canvas.create_window(100, 140, window=labelNum2)

labelNum3 = tk.Label(root, text='Result:')


labelNum3.config(font= ('helvetica', 10))
canvas.create_window(100, 240, window=labelNum3)

def add ():


v1 = entry1.get ()
v2 = entry2.get ()

labelResultAdd = tk.Label(root, text= float(v1)+float(v2),font=('helvetica', 10, 'bold'),bg='white')


canvas.create_window(210, 240, window=labelResultAdd)

buttonAdd = tk.Button(text='+', command=add, bg='blue', fg='white', font=('helvetica', 9, 'bold'),


width = 5)
canvas.create_window(90, 190, window=buttonAdd
def sub ():
v1 = entry1.get ()
v2 = entry2.get ()
P a g e | 41

labelResultSub = tk.Label(root, text= float(v1)-float(v2),font=('helvetica', 10, 'bold'),bg='white')


canvas.create_window(210, 240, window=labelResultSub)

buttonSub = tk.Button(text='–', command=sub, bg='blue', fg='white', font=('helvetica', 9, 'bold'),


width = 5)
canvas.create_window(140, 190, window=buttonSub)

def mul ():


v1 = entry1.get ()
v2 = entry2.get ()

labelResultMul = tk.Label(root, text= float(v1)*float(v2),font=('helvetica', 10, 'bold'),bg='white')


canvas.create_window(210, 240, window=labelResultMul)

buttonMul = tk.Button(text='x', command=mul, bg='blue', fg='white', font=('helvetica', 9, 'bold'),


width = 5)
canvas.create_window(190, 190, window=buttonMul)

def div ():


v1 = entry1.get ()
v2 = entry2.get ()
labelResultDiv = tk.Label(root, text= float(v1)/float(v2),font=('helvetica', 10, 'bold'),bg='white')
canvas.create_window(210, 240, window=labelResultDiv)

buttonDiv = tk.Button(text='/', command=div, bg='blue', fg='white', font=('helvetica', 9, 'bold'), width


= 5)
canvas.create_window(240, 190, window=buttonDiv)

root.mainloop()
P a g e | 42

DO-IT-YOURSELF
P a g e | 43

Do-It-Yourself

1 - CREATE COMMAND LINE INTERFACE APPLICATION (CLI) BASED ON CRUDS


APPLICATION

You’ve have been asked to design a CLI application for Kitty Toys Shop which helps
management team of a shop to collect and keep a record of all purpose of their customers.
To do that, you will need to create a database and apply CRUDS (C reate, R ead, U pdate, D
elete, and S earch) to allow management team to manage the customer information.
By using MySQL connector, construct a Python program to create a database name ‘Toys_DB’.
Then write a program that can accept input from user which is customer name and customer
address. This record must be saved in the table name ‘CUSTOMERS’.

Program Code
import mysql.connector
import os
db = mysql.connector.connect(
host="localhost",
user="root",
password=""
database="Toys_DB"
)
def insert_data(db):
name = input("Enter your name: ")
address = input("Enter your address: ")
val = (name, address)
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
cursor.execute(sql, val)
db.commit()
print("{} data successufully saved!".format(cursor.rowcount))

def show_data(db):
cursor = db.cursor()
sql = "SELECT * FROM customers"
cursor.execute(sql)
results = cursor.fetchall()
if cursor.rowcount < 0:
print("No record")
else:
for data in results:
print(data)

def update_data(db):
cursor = db.cursor()
P a g e | 44

show_data(db)
customer_id = input("choose customer id> ")
name = input("New Name: ")
address = input("New Address: ")
sql = "UPDATE customers SET name=%s, address=%s WHERE
customer_id=%s"
val = (name, address, customer_id)
cursor.execute(sql, val)
db.commit()
print("{} data successfully
updated!".format(cursor.rowcount))

def delete_data(db):
cursor = db.cursor()
show_data(db)
customer_id = input("choose customer id > ")
sql = "DELETE FROM customers WHERE customer_id=%s"
val = (customer_id,)
cursor.execute(sql, val)
db.commit()
print("{} data successfully
deleted!".format(cursor.rowcount))

def search_data(db):
cursor = db.cursor()
keyword = input("Keyword: ")
sql = "SELECT * FROM customers WHERE name LIKE %s OR address
LIKE %s"
val = ("%{}%".format(keyword), "%{}%".format(keyword))
cursor.execute(sql, val)
results = cursor.fetchall()
if cursor.rowcount < 0:
print("No record")
else:
for data in results:
print(data)
def show_menu(db):
print("=== KITTY TOYS SHOP APPLICATION ===")
print("1. Insert Data")
print("2. View Data")
print("3. Update Data")
print("4. Delete Data")
print("5. Search Data")
print("0. Exit")
print("------------------")
menu = input("Choose Menu> ")

#clear screen
os.system("clear")
if menu == "1":
insert_data(db)
elif menu == "2":
show_data(db)
elif menu == "3":
update_data(db)
elif menu == "4":
delete_data(db)
P a g e | 45

elif menu == "5":


search_data(db)

elif menu == "0":


exit()
else:
print("Wrong Menu!")

if __name__ == "__main__":
while(True):
show_menu(db)
P a g e | 46

Do -It-Yourself

2 - CREATE APPLICATION FORM USING TKINTER WIDGETS AND DATABASE


INTEGRATION

You’ve have been asked to design an application, the Employee Registration Form, which
helps management team of a company to collect and keep a record of all their existing
members for identification and recording purposes about their employees. To do that, you
will need to create a window with widgets to allow employee to fill in their details. This is to
keep track of their existing records in the event of anything important that may arise that
would warrant the use of such information. This has been the standard process of employers
worldwide and are intended to record consistent data of their employees.

Construct a Python program (using Tkinter module) to record information in a database


named Employee with two table User (Username and Password) and Staff (Name, Age, Email,
Gender, City and State). You need to show the results of the application as shown in Figure
1.0 and Figure 2.0.

Figure 1.0 Login Form


P a g e | 47

Login Form Code


from tkinter import *
from tkinter import messagebox
import mysql.connector as mysql

def login ():


uname=username.get ()
pw=password.get ()
if (uname==""or pw==""):
messagebox.showinfo("Login Status", "Please enter the
correct username and password")
elif(uname==username.get () or pw==password.get()):
messagebox.showinfo("Login Status", "Correct username and
password")
root.destroy()
import register_pbt2
else:
con=mysql.connect(host="localhost", user="root",
password="", database="employee")
cursor=con.cursor()
cursor.execute("select * from user")

con.close();

root = Tk ()
root.title("Login Form")

canvas1 = Canvas (root, width = 350, height = 280)


Canvas1 = Canvas(root)
canvas1.pack()

subtitle = Label (root, text="Please enter your details to login”,


font=("Helvetica",12), foreground = '#0000e0'). place (x=55, y=8)

#Username
label_Uname= Label (root, text="Username*”, font=("Helvetica",12))
label_Uname.place(x=130, y=70)
username = Entry (root, font=("Helvetica",15), bg="white")
username.place(x=50, y=100, width=250, height=20)

#Password
label_pw= Label (root, text="Password*", font=("arial",12))
label_pw.place(x=130,y=130)
password = Entry (root, font=("Helvetica",12), bg="white",show='*')
password.place(x=50, y=160, width=250, height=20)

#Button
submit = Button (root, cursor="hand2", text="Login",bd=2,
font=("Helvetica",12),width=12, activebackground='#002e63’,
activeforeground='white',command=login).place(x=115,y=210)

root.mainloop()
P a g e | 48

Figure 2.0: Registration Form


Registration Form Code
from tkinter import *
from tkinter.ttk import Combobox
from tkinter import messagebox
import mysql.connector as mysql

def register ():


NAME=name.get ()
AGE=age.get ()
EMAIL=email.get ()
GENDER=gender.get ()
CITY=city.get ()
STATE=state.get ();

if (NAME=="" or AGE==""or EMAIL==""or GENDER==""or CITY=="" or


STATE==""):
messagebox.showinfo("Registration Status", "All Fields are
required")
else:
con=mysql.connect(host="localhost", user="root",
password="", database="employee")
cursor=con.cursor()
cursor.execute("insert into staff values('"+ NAME +"','"+
AGE +"','"+EMAIL+"','"+str(GENDER)+"',
'"+CITY+"','"+STATE+"')")
cursor.execute("commit");
messagebox.showinfo("Registration Status", "Inserted
Successfully");
con.close();
P a g e | 49

root = Tk ()
root.title("Registration Form")
root.geometry("470x470")
subtitle= Label (root, text="Please enter your details to
login",font=("Helvetica",12),foreground='black',
bg="#009e00”, width=550, height=1). pack ()
canvas1 = Canvas (root, width = 470, height = 470)
Canvas1 = Canvas(root)
canvas1.pack()

lblName=Label(root,text="Name*",font=("Helvetica",11))
lblName.place(x=20, y=60)
name=Entry(root,font=("Helvetica",11))
name.place(x=120,y=52, width=230, height=25)

lblAge=Label(root,text="Age*",font=("Helvetica",11))
lblAge.place(x=20, y=110)
age=Entry(root,font=("Helvetica",11))
age.place(x=120,y=102, width=230, height=25)

lblEmail=Label(root,text="Email*",font=("Helvetica",11))
lblEmail.place(x=20, y=160)
email=Entry(root,font=("Helvetica",11))
email.place(x=120,y=152, width=230, height=25)

lblGen=Label(root,text="Gender*",font=("Helvetica",11))
lblGen.place(x=20, y=210)
gender=IntVar ()
gender.set (1)
r1=Radiobutton (root, text="Male",font=("Helvetica",11)
,variable=gender,value=1)
r2=Radiobutton (root, text="Female",font=("Helvetica",11),
variable=gender,value=2)
r1. place (x=130, y=210)
r2. place (x=240, y=210)

lblCity=Label(root,text="City*",font=("Helvetica",11))
lblCity.place(x=20, y=260)
var1 = StringVar ()
var1.set ("Alor Gajah")
data= ("Alor Gajah", "Kuantan", "Kuala Terengganu",
"Kuching","Seremban")
city=Combobox (root, values=data,width=40)
city.place(x=120, y=260)

lblCity=Label(root,text="State*",font=("Helvetica",11))
lblCity.place(x=20, y=310)
var2 = StringVar ()
var2.set("Melaka")
data= ("Melaka", "Negeri Sembilan", "Pahang",
"Sarawak","Terengganu")
state=Combobox (root, values=data,width=40)
state.place(x=120, y=310)
P a g e | 50

btnReg=Button (root, text="Register”, font=("Helvetica",12),


width=12, height=1, bd=3, bg="#009e00",
activebackground='#008000’,
activeforeground='white',command=register)
btnReg.place(x=120, y=380)

root.mainloop()
P a g e | 51

REFFERENCES

David, L. (2018), Tkinter GUI Programming by Example, Packt Publishing Ltd. ISBN 978-1-
78862-748-1

David, A., Dan, B., Joanna, J. and Fletcher H. (2020), Python Basics: A Practical Introduction
to Python 3, ISBN: 9781775093336
https://static.realpython.com/python-basics-sample-chapters.pdf

Ayesha Tariq (2020), Python SQLite3 tutorial (Database programming), Retrieve from
https://likegeeks.com/python-sqlite3-tutorial/

Chaitanya, B. (2020), Python and MySQL Database: A Practical Introduction, Retrieve from
https://realpython.com/python-mysql/

Computer Hope (2021), GUI, Retrieve from


https://www.computerhope.com/jargon/gui.htm

David, A. (2021), Python GUI Programming with Tkinter, Retrieve from


https://realpython.com/python-gui-tkinter/

PYnative (2021), Python MySQL Database Connection using MySQL Connector, Retrieve from
https://pynative.com/python-mysql-database-connection/

Python Tutorial (2021), Tkinter, Retrieve from https://www.pythontutorial.net/tkinter/


Terbitan

MUADZAM SHAH

View publication stats

You might also like