Ebook Python GUI Programming With Tkinter
Ebook Python GUI Programming With Tkinter
net/publication/371730724
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.
GUI Programming
with Tkinter
Penulis:
Siti Zaharah Binti Sidek
Mastura Binti Ramli
Siti Norhidayah Binti Saad
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
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
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
CHAPTER 1
Page |1
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
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.
CHAPTER 2
Page |5
CHAPTER 2 - TKINTER
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.
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
Important:
pack (), place (), and grid () should not be combined in the same master window.
Instead choose one and stick with it.
Page |8
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.
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
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.
3.2 SQLite
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:
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:
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.
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
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.
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.
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.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.
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)
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
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.
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.
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
TUTORIAL
P a g e | 23
TUTORIAL
1.1 - Create Python database using SQLite
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
3. INSERT Operation
4. SELECT Operation
5. UPDATE Operation
6. DELETE Operation
TUTORIAL 1.2
1.2 - Create Python database using MySQL
iii. Setting the server based on your own setting for username and password.
Basically, the username is root.
P a g e | 30
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:
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.
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:
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:
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:
import tkinter as tk
from tkinter import ttk
# root window
root = tk.Tk()
root.geometry("240x100")
root.title('Login Form')
root.resizable(0, 0)
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()
root.mainloop()
P a g e | 42
DO-IT-YOURSELF
P a g e | 43
Do-It-Yourself
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
if __name__ == "__main__":
while(True):
show_menu(db)
P a g e | 46
Do -It-Yourself
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.
con.close();
root = Tk ()
root.title("Login Form")
#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
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
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/
PYnative (2021), Python MySQL Database Connection using MySQL Connector, Retrieve from
https://pynative.com/python-mysql-database-connection/
MUADZAM SHAH