Download as pdf or txt
Download as pdf or txt
You are on page 1of 112

Integrated Programming

and Technologies 2
Oldarico Pigon
College of Computer Studies
IPT 2 2

Week 1
Lesson:

 Simple CRUD Console Application with MySQL and Python

Objectives:

 Developing a simple application with create, read, update, and delete feature with Python and
MySQL.

Topics:
 CRUD

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 3

CRUD
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 4

CRUD
Creating and Calling a Function

In Python a function is defined using the def keyword:

def say_myname():
print("You are Oldarico Pigon")

say_myname()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 5

CRUD
 Imports

 Import using import mysql.connector as mysql statement so you can use this module's
methods to communicate with the MySQL database.

 Import using from mysql.connector import Error forces you to generate an Error statement
if the compiler detects an error in your MySQL syntax.

import mysql.connector as mysql


from mysql.connector import Error

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 6

CRUD
 Install package mysql-connector-python.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 7

CRUD
 Make a function called "insert.“

def insert():

 Create three inputs within a function.

def insert():
fname = input("Enter First Name: ")
mname = input("Enter Middle Name: ")
lname = input("Enter Last Name: ")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 8

CRUD
 Python input() function is used to take user input. By default, it returns the user input in form
of a string.

name = input('Enter your name:')


print('Good Morning, ' + name)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 9

CRUD
 Try Except

The try block lets you test a block of code for errors.

The except block lets you handle the error.

try:
print(name)
except:
print("The Variable is not set")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 10

CRUD
 Create a try except

 Insert the following code within the try keyword:

try:
conn = mysql.connect(host="localhost", username="root", password="", database="db_test")
sql = "INSERT INTO tbl_account (firstname, middlename, lastname) VALUES ('{}', '{}', '{}')".format(fname, mname, lname)
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 11

CRUD
 To create a connection between the MySQL database and Python, the connect() method of
mysql.connector module is used. We pass the database details like HostName, username,
and the password in the method call, and then the method returns the connection object.

 A cursor is an object which helps to execute the query and fetch the records from the database.

 The commit() method lets a user permanently save all the changes made in the transaction of
a database or table.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 12

CRUD
 Insert the following code within the except keyword:

except Error:
print("Error: ").format(Error)

 Call the insert() function to insert data.

insert()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 13

CRUD
import mysql.connector as mysql
from mysql.connector import Error

def insert():
fname = input("Enter First Name: ")
mname = input("Enter Middle Name: ")
lname = input("Enter Last Name: ")

try:
conn = mysql.connect(host="localhost", username="root", password="", database="db_test")
sql = "INSERT INTO tbl_account (firstname, middlename, lastname) VALUES ('{}', '{}', '{}')".format(fname, mname, lname)
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()

except Error:
print("Error: ").format(Error)

insert()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 14

CRUD
 Create a function called select().

def select():

 Create try except keyword and Insert the following code within the try keyword:

try:
conn = mysql.connect(host="localhost", username="root", password="", database="db_test")
sql = "SELECT * FROM tbl_account"
cursor = conn.cursor()
cursor.execute(sql)
result = cursor.fetchall()

print("Number of records: " + str(cursor.rowcount))

for row in result:


print("ID: {} \nFirst Name: {} \nMiddle Name: {} \nLast Name: {} \nDate Inserted: {}".format(row[0], row[1], row[2], row[3], row[4]))

cursor.close()
conn.close()
Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 15

CRUD
 cursor.fetchall() fetches all the rows of a query result. It returns all the rows as a list of
tuples. An empty list is returned if there is no record to fetch. cursor.

 cursor.rowcount returns the number of rows returned for SELECT statements, or the
number of rows affected by DML statements such as INSERT or UPDATE .

 The str() function converts the specified value into a string.

x = 10
print("This is string " + str(x))

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 16

CRUD
 A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).

planets = ["Earth", "Jupiter", "Saturn"]


for x in planets:
print(x)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 17

CRUD
 Insert the following code within the except keyword:

except Error:
print("Error: ").format(Error)

 Call the select() function to insert data.

select()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 18

CRUD
import mysql.connector as mysql
from mysql.connector import Error

def select():
try:
conn = mysql.connect(host="localhost", username="root", password="", database="db_test")
sql = "SELECT * FROM tbl_account"
cursor = conn.cursor()
cursor.execute(sql)
result = cursor.fetchall()

print("Number of records: " + str(cursor.rowcount))

for row in result:


print("ID: {} \nFirst Name: {} \nMiddle Name: {} \nLast Name: {} \nDate Inserted: {}".format(row[0], row[1], row[2], row[3], row[4]))

cursor.close()
conn.close()

except Error:
print("Error: ").format(Error)

select()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 19

CRUD
 Create a function called delete()

def delete():

 Create input() for the ID that will be deleted.

ID = input("Enter Delete ID: ")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 20

CRUD
 Create try except keyword and Insert the following code within the try keyword:

try:
conn = mysql.connect(host="localhost", username="root", password="", database="db_test")
sql = "DELETE FROM tbl_account WHERE ID = {}".format(ID)
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 21

CRUD
 Insert the following code within the except keyword:

except Error:
print("Error: ").format(Error)

 Call the select() function to insert data.

delete()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 22

CRUD
import mysql.connector as mysql
from mysql.connector import Error

def delete():
ID = input("Enter Delete ID: ")

try:
conn = mysql.connect(host="localhost", username="root", password="", database="db_test")
sql = "DELETE FROM tbl_account WHERE ID = {}".format(ID)
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()

except Error:
print("Error: ").format(Error)

delete()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 23

CRUD
def update():
ID = input("Enter ID: ")
fname = input("Enter New First Name: ")
mname = input("Enter New Middle Name: ")
lname = input("Enter New Last Name: ")

try:
conn = mysql.connect(host="localhost", username="root", password="", database="db_test")
sql = "UPDATE tbl_account SET firstname='{}', middlename='{}', lastname='{}' WHERE ID = {}".format(fname, mname, lname, ID)
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()

except Error as error:


print("Error: {}".format(error))

update()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 24

Quiz 1
Directions:
 Your work should be submitted as a recorded video.
 Pass till the 19th of August.
 50 pts

Create a program that will allow you to insert, update, delete and select your name, year, and
section.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 25

Week 2
Lesson:

 Tkinter Button, Label, and Entry widget.

Objectives:

 Understanding the Tkinter GUI and widgets that we can use to create Tkinter applications, as
well as widget options.

Topics:
 Tkinter GUI, Button Widget, Label Widget, and Entry Widget.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 26

Tkinter GUI
 To create GUI application, we need to start by importing Tkinter modules.

from tkinter import *

 root is the root window into which all other widgets go. It is called Master, that is the parameter
used to represent the parent window.

root = Tk()

 The title() in tkinter refers to a name assigned to the application window.

root.title("Title goes here.")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 27

Tkinter GUI
 geometry() is used to set the dimensions of the Tkinter window and is used to set the position of
the main window on the user's desktop.

root.geometry

 mainloop() is a method on the main window which we execute when we want to run our
application.

root.mainloop()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 28

Tkinter GUI
 Iconbitmap(bitmap) sets the icon of the window/frame widget to bitmap . The bitmap must be an
ico type, but not png or jpg type, otherwise, the image will not display as the icon.

 In your project, create a new directory named “img" and save any .ico files inside.

root.iconbitmap("img/yt.ico")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 29

Button Widget
Button widget.

 The Button widget is used to add buttons in a Python application. These buttons can display
text or images that convey the purpose of the buttons. You can attach a function or a method to
a button which is called automatically when you click the button.

mybutton = Button(root, text="Click Me")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 30

Button Widget
Options and Description:

1. Activebackground - Background color when the button is under the cursor.

2. Activeforeground - Foreground color when the button is under the cursor.

3. Bd - Border width in pixels. Default is 2.

4. Bg - Normal background color.

5. Command - Function or method to be called when the button is clicked.

6. Fg - Normal foreground (text) color.

7. Font - Text font to be used for the button's label.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 31

Button Widget
8. Height - Height of the button in text lines (for textual buttons) or pixels (for images).

9. Highlightcolor - The color of the focus highlight when the widget has focus.

10. Image - Image to be displayed on the button (instead of text).

11. Justify - How to show multiple text lines: LEFT to left-justify each line; CENTER to center them;
or RIGHT to right-justify.

12. Padx - Additional padding left and right of the text.

13. Pady - Additional padding above and below the text.

14. Relief - Relief specifies the type of the border. Some of the values are SUNKEN, RAISED,
GROOVE, and RIDGE.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 32

Button Widget
15. Underline - Default is -1, meaning that no character of the text on the button will be underlined.
If nonnegative, the corresponding text character will be underlined.

16. State - Set this option to DISABLED to gray out the button and make it unresponsive. Has the
value ACTIVE when the mouse is over it. Default is NORMAL.

17. Width - Width of the button in letters (if displaying text) or pixels (if displaying an image).

18. Wraplength - If this value is set to a positive number, the text lines will be wrapped to fit within
this length.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 33

Button Widget
 Activebackground - Background color when the button is under the cursor.

btnSubmit = Button(root, text="Submit", activebackground="#fcba03")


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 34

Button Widget
 Activeforeground - Foreground color when the button is under the cursor.

btnSubmit = Button(root, text="Submit", activeforeground="blue")


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 35

Button Widget
 Bd - Border width in pixels. Default is 2.

btnSubmit = Button(root, text="Submit", bd=5)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 36

Button Widget
 Bg - Normal background color.

btnSubmit = Button(root, text="Submit", bg="yellow")


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 37

Button Widget
 Fg - Normal foreground (text) color.

btnSubmit = Button(root, text="Submit", fg="red")


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 38

Button Widget
 Font - Text font to be used for the button's label.

btnSubmit = Button(root, text="Submit", font="courier 22 italic")


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 39

Button Widget
 Height - Height of the button in text lines (for textual buttons) or pixels (for images).

btnSubmit = Button(root, text="Submit", height=10)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 40

Button Widget
 Justify - How to show multiple text lines: LEFT to left-justify each line; CENTER to center them;
or RIGHT to right-justify.

btnSubmit = Button(root, text="This\nis\na\nbuton", justify="right")


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 41

Button Widget
 Padx - Additional padding left and right of the text.

btnSubmit = Button(root, text="Submit", padx=50)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 42

Button Widget
 Pady - Additional padding above and below the text.

btnSubmit = Button(root, text="Submit", pady=50)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 43

Button Widget
 Relief - Relief specifies the type of the border. Some of the values are SUNKEN, RAISED,
GROOVE, and RIDGE.

 Use bd to increase the border size.

btnSubmit = Button(root, text="Submit", relief="sunken", bd=5)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 44

Button Widget
 Underline - Default is -1, meaning that no character of the text on the button will be underlined.
If nonnegative, the corresponding text character will be underlined.

btnSubmit = Button(root, text="Submit", underline=0)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 45

Button Widget
 State - Set this option to DISABLED to gray out the button and make it unresponsive. Has the
value ACTIVE when the mouse is over it. Default is NORMAL.

btnSubmit = Button(root, text="Submit", state="disabled")


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 46

Button Widget
 Width - Width of the button in letters (if displaying text) or pixels (if displaying an image).

btnSubmit = Button(root, text="Submit", width=50)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 47

Button Widget
 Wraplength - If this value is set to a positive number, the text lines will be wrapped to fit within
this length.

btnSubmit = Button(root, text="Submit", wraplength=1)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 48

Button Widget
 Image - Image to be displayed on the button (instead of text).

 Adding an image into your button.

 Must be PNG type.

images = PhotoImage(file="img/Red_button.png")

btnSubmit = Button(root, text="Submit", image=images)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 49

Button Widget
 Command - Function or method to be called when the button is clicked.

def clickme():
lbl = Label(root, text="Hello World!")
lbl.pack()

btnSubmit = Button(root, text="Submit", command=clickme)


btnSubmit.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 50

Label Widget
Label widget.

 This widget implements a display box where you can place text or images. The text displayed
by this widget can be updated at any time you want.

my_label = Label(root, text="This is a text.")


my_label.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 51

Label Widget
Options and Description:

1. Anchor - This options controls where the text is positioned if the widget has more space than the
text needs. The default is anchor=CENTER, which centers the text in the available space.

2. Bg - The normal background color displayed behind the label and indicator.

3. Bitmap - Set this option equal to a bitmap or image object and the label will display that graphic.

4. Bd - The size of the border around the indicator. Default is 2 pixels.

5. 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.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 52

Label Widget
6. Font - If you are displaying text in this label (with the text or textvariable option, the font option
specifies in what font that text will be displayed.

7. 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.

8. Height - The vertical dimension of the new frame.

9. Image - To display a static image in the label widget, set this option to an image object.

10. 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.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 53

Label Widget
11. Padx - Extra space added to the left and right of the text within the widget. Default is 1.

12. Pady - Extra space added above and below the text within the widget. Default is 1.

13. Relief - Specifies the appearance of a decorative border around the label. The default is FLAT; for
other values.

14. 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.

15. Textvariable - To slave the text displayed in a label widget to a control variable of class StringVar,
set this option to that variable.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 54

Label Widget
16. Underline - You can display an underline (_) below the nth letter of the text, counting from 0, by
setting this option to n. The default is underline=-1, which means no underlining.

17. Width - Width of the label in characters (not pixels!). If this option is not set, the label will be sized
to fit its contents.

18. Wraplength - You can limit the number of characters in each line by setting this option to the
desired number. The default value, 0, means that lines will be broken only at newlines.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 55

Label Widget
 Anchor - This options controls where the text is positioned if the widget has more space than
the text needs. The default is anchor=CENTER, which centers the text in the available space.

 You need to set the width and height of the label for it to work.

my_label = Label(root, text="This is a text.", anchor="center", width=20, height=10, bg="green")


my_label.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 56

Label Widget
 Bitmap - Set this option equal to a bitmap or image object and the label will display that graphic.

b1 = Label(root, bitmap="error")
b2 = Label(root, bitmap="hourglass")
b3 = Label(root, bitmap="info")
b4 = Label(root, bitmap="question")
b5 = Label(root, bitmap="warning")

b1.pack()
b2.pack()
b3.pack()
b4.pack()
b5.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 57

Label Widget
 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.

greet = StringVar()
greet.set("Hello World")

label = Label(root, textvariable=greet, cursor="dot")


label.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 58

Label Widget
 Python Tkinter supports quite a number of different mouse cursors available. The exact
graphic may vary according to your operating system.

1. Arrow 7. Fleur 13. Shuttle 19. Tcross

2. Circle 8. Heart 14. Sizing 20. Trek

3. Clock 9. Man 15. Spider 21. Watch

4. Cross 10. Mouse 16. Spraycan

5. Dotbox 11. Pirate 17. Star

6. Exchange 12. Plus 18. Target

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 59

Label Widget
 Textvariable - To slave the text displayed in a label widget to a control variable of class
StringVar, set this option to that variable.

greet = StringVar()
greet.set("Hello World")

label = Label(root, textvariable=greet)


label.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 60

Entry Widget
Entry widget.

 The Entry widget is used to provide the single line text-box to the user to accept a value from
the user. We can use the Entry widget to accept the text strings from the user. It can only be
used for one line of text from the user.

textbox = Entry(root)
textbox.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 61

Entry Widget
Options and Description:

1. Bg - The normal background color displayed behind the label and indicator.

2. Bd - The size of the border around the indicator. Default is 2 pixels.

3. 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.

4. Font - The font used for the text.

5. 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.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 62

Entry Widget
6. Fg - The color used to render the text.

7. Highlightcolor - The color of the focus highlight when the entry has the focus.

8. Justify - If the text contains multiple lines, this option controls how the text is justified: CENTER,
LEFT, or RIGHT.

9. Relief - With the default value, relief=FLAT, the entry does not stand out from its background. You
may set this option to any of the other styles

10. Selectbackground - The background color to use displaying selected text.

11. Selectborderwidth - The width of the border to use around selected text. The default is one pixel.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 63

Entry Widget
12. Selectforeground - The foreground (text) color of selected text.

13. 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="*".

14. State - The default is state=NORMAL, but you can use state=DISABLED to gray out the control
and make it unresponsive. If the cursor is currently over the entry, the state is ACTIVE.

15. Textvariable - 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.

16. Width - The default width of a entry is determined by the size of the displayed image or text. You
can set this option to a number of characters and the entry will always have room for that many
characters.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 64

Entry Widget
 Selectbackground - The background color to use displaying 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.

text_here = Entry(root, selectforeground="green", selectbackground="pink", selectborderwidth=10)


text_here.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 65

Entry Widget
 Highlightcolor - The color of the focus highlight when the entry has the focus.

 The figures show what happens when the Entry is clicked and when it is not.

text_here = Entry(root, highlightcolor="green", highlightthickness=10, highlightbackground="pink")


text_here.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 66

Entry Widget
 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="*".

text_here = Entry(root, show="*")


text_here.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 67

Entry Widget
 State - The default is state=NORMAL, but you can use state=DISABLED to gray out the control
and make it unresponsive. If the cursor is currently over the entry, the state is ACTIVE.

text_here = Entry(root, state="disabled")


text_here.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 68

Entry Widget
 Textvariable - 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.

x = StringVar()
x.set("Hello World")

text_here = Entry(root, textvariable=x)


text_here.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 69

Quiz 2
Directions:
 Your work should be submitted as a recorded video.
 NA
 100 pts

Create a program that will allow the user to input and display your name, year, and section when
the button is clicked.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 70

Week 3
Lesson:

 Tkinter Treeview, and Grid System.

Objectives:

 Understanding how Tkinter's grid system works so that we can properly organize and position
our widgets, as well as learning how Treeview works to insert and delete data within it.

Topics:
 Grid System, Treeview Widget

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 71

Grid System
 Pack - This method packs widgets relative to the earlier widget. Tkinter literally packs all the
widgets one after the other in a window. We can use options like fill, expand, and side to control
this geometry manager.

label = Label(root, text="EXAMPLE TEXT")


label.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 72

Grid System
Here is the list of possible options for pack method:

 expand − When set to true, widget expands to fill any space not otherwise used in widget's
parent.

 fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its
own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or
BOTH (fill both horizontally and vertically).

 side − Determines which side of the parent widget packs against: TOP (default), BOTTOM,
LEFT, or RIGHT.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 73

Grid System
 side − Determines which side of the parent widget packs against: TOP (default), BOTTOM,
LEFT, or RIGHT.

label1 = Label(root, text="EXAMPLE TEXT", bg="pink")


label1.pack(side="left")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 74

Grid System
 expand − When set to true, widget expands to fill any space not otherwise used in widget's
parent.

 fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its
own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or
BOTH (fill both horizontally and vertically).

label1 = Label(root, text="EXAMPLE TEXT", bg="pink")


label1.pack(side="top", fill="y", expand="yes")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 75

Grid System
 The grid() geometry manager organises widgets in a table-like structure in the parent widget.
The master widget is split into rows and columns, and each part of the table can hold a widget.

label1 = Label(root, text="ROW 1 COL 1", bg="pink")


label2 = Label(root, text="ROW 1 COL 2", bg="orange")
label3 = Label(root, text="ROW 1 COL 3", bg="lightgreen")
label4 = Label(root, text="ROW 2 COL 1", bg="lightblue")

label1.grid(row=0, column=0)
label2.grid(row=0, column=1)
label3.grid(row=0, column=2)
label4.grid(row=1, column=0)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 76

Grid System
Here is the list of possible options for grid method:

 column − The column to put widget in; default 0 (leftmost column).

 columnspan − How many columns widget occupies; default 1.

 ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's
borders.

 padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders.

 row − The row to put widget in; default the first row that is still empty.

 rowspan − How many rows widget occupies; default 1.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 77

Grid System
 columnspan − How many columns widget occupies; default 1.

label1 = Label(root, text="ROW 1 COL 1", bg="pink")


label2 = Label(root, text="ROW 1 COL 2", bg="orange")
label3 = Label(root, text="ROW 1 COL 3", bg="lightgreen")
label4 = Label(root, text="ROW 2 COL 1", bg="lightblue")

label1.grid(row=0, column=0)
label2.grid(row=0, column=1)
label3.grid(row=0, column=2)
label4.grid(row=1, column=0, columnspan=3)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 78

Grid System
 ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's
borders.

label1 = Label(root, text="ROW 1 COL 1", bg="pink")


label2 = Label(root, text="ROW 1 COL 2", bg="orange")
label3 = Label(root, text="ROW 1 COL 3", bg="lightgreen")
label4 = Label(root, text="ROW 2 COL 1", bg="lightblue")

label1.grid(row=0, column=0)
label2.grid(row=0, column=1)
label3.grid(row=0, column=2)
label4.grid(row=1, column=0, columnspan=3, ipadx=20, ipady=20)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 79

Grid System
 padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders.

label1 = Label(root, text="ROW 1 COL 1", bg="pink")


label2 = Label(root, text="ROW 1 COL 2", bg="orange")
label3 = Label(root, text="ROW 1 COL 3", bg="lightgreen")
label4 = Label(root, text="ROW 2 COL 1", bg="lightblue")

label1.grid(row=0, column=0)
label2.grid(row=0, column=1)
label3.grid(row=0, column=2)
label4.grid(row=1, column=0, columnspan=3, padx=20, pady=20)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 80

Grid System
 sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is centered
in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE,
and SW, compass directions indicating the sides and corners of the cell to which widget sticks.

label1 = Label(root, text="ROW 1 COL 1", bg="pink")


label2 = Label(root, text="ROW 1 COL 2", bg="orange")
label3 = Label(root, text="ROW 1 COL 3", bg="lightgreen")
label4 = Label(root, text="ROW 2 COL 1", bg="lightblue")

label1.grid(row=0, column=0)
label2.grid(row=0, column=1)
label3.grid(row=0, column=2)
label4.grid(row=1, column=0, columnspan=3, sticky="e")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 81

Grid System
 The place() manager organises widgets by placing them in a specific position in the parent
widget.

ID = Label(root, text="ID:", bg="pink")


fname = Label(root, text="FIRST NAME:", bg="orange")
mname = Label(root, text="MIDDLE NAME:", bg="lightgreen")
lname = Label(root, text="LAST NAME:", bg="lightblue")

ID.pack(), fname.pack(), mname.pack(), lname.pack()

ID.place(x=10, y=10)
fname.place(x=10, y=40)
mname.place(x=10, y=70)
lname.place(x=10, y=100)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 82

Grid System
Here is the list of possible options for place method:

 anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or
SW, compass directions indicating the corners and sides of widget; default is NW (the upper left
corner of widget)

 bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside
(ignoring the parent's border); OUTSIDE otherwise.

 height, width − Height and width in pixels.

 relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height
and width of the parent widget.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 83

Grid System
 relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the
height and width of the parent widget.

 x, y − Horizontal and vertical offset in pixels.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 84

Grid System
 relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the
height and width of the parent widget.

ID = Label(root, text="ID:", bg="pink")


fname = Label(root, text="FIRST NAME:", bg="orange")
mname = Label(root, text="MIDDLE NAME:", bg="lightgreen")
lname = Label(root, text="LAST NAME:", bg="lightblue")

ID.pack(), fname.pack(), mname.pack(), lname.pack()

ID.place(relx=0.1, rely=0.1)
fname.place(relx=0.1, rely=0.3)
mname.place(relx=0.1, rely=0.5)
lname.place(relx=0.1, rely=0.7)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 85

Grid System
 height, width − Height and width in pixels.

ID = Label(root, text="ID:", bg="pink")


fname = Label(root, text="FIRST NAME:", bg="orange")
mname = Label(root, text="MIDDLE NAME:", bg="lightgreen")
lname = Label(root, text="LAST NAME:", bg="lightblue")

ID.pack(), fname.pack(), mname.pack(), lname.pack()

ID.place(relx=0.1, rely=0.1, width=200, height=30)


fname.place(relx=0.1, rely=0.3)
mname.place(relx=0.1, rely=0.5)
lname.place(relx=0.1, rely=0.7)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 86

Grid System
 relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height
and width of the parent widget.

ID = Label(root, text="ID:", bg="pink")


fname = Label(root, text="FIRST NAME:", bg="orange")
mname = Label(root, text="MIDDLE NAME:", bg="lightgreen")
lname = Label(root, text="LAST NAME:", bg="lightblue")

ID.pack(), fname.pack(), mname.pack(), lname.pack()

ID.place(relx=0.1, rely=0.1, width=200, height=30, relheight=0.2, relwidth=0.2)


fname.place(relx=0.1, rely=0.3)
mname.place(relx=0.1, rely=0.5)
lname.place(relx=0.1, rely=0.7)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 87

Treeview Widget
Treeview widget.

 Python Tkinter Treeview is a tabular representation of the data as it has all the properties of the
table. Treeview has rows, columns, and heading. Rows: Horizontal space determined by the
data. More data more rows. Columns: vertical space determines the heading.

from tkinter import ttk

trv = ttk.Treeview(root, columns=(1, 2, 3, 4), show="headings")


trv.pack()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 88

Treeview Widget
Options and Description:

1. columns - An array of column names for widget.

2. displaycolumns - An array of column names or indices specifying columns to be displayed. Use


#all for all.

3. height - Height for widget.

4. selectmode - Selection mode which can be extended, browse, or none.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 89

Treeview Widget
 heading method is used to create a column headings for Treeview widget

 columns - An array of column names for widget.

 Show option is used to show the headers of Treeview.

trv = ttk.Treeview(root, columns=(0, 1, 2, 3), show="heading")


trv.pack()

trv.heading(0, text="ID", anchor="w")


trv.heading(1, text="FIRST NAME", anchor="w")
trv.heading(2, text="MIDDLE NAME", anchor="w")
trv.heading(3, text="LAST NAME", anchor="w")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 90

Treeview Widget
 In Treeview, the insert method is used to insert a new row.

trv.insert(parent="", index="end", values=(1, "Oldarico", "Balagon", "Pigon"))

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 91

Treeview Widget
 the parent is the item ID of the parent item, or the empty string to create a new top-level item.

 the index is an integer or the value end, specifying wherein the list of parent's children to insert
the new item.

 iid is used as the item identifier, iid must not already exist in the tree.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 92

Treeview Widget
 We can also use a for loop to extract data from a collection and display all items in Treeview.

records = [
[2, "Danica Karen", "Obra", "Talon"],
[3, "Kairi", "Ygnacio ", "Rayosdelsol"],
[4, "Setsuna", "Dogie", "Ignacio"],
[5, "Manjean" ,"Faduga", "Faldas"]
]

for row in records:


trv.insert(parent="", index="end", values=(row[0], row[1], row[2], row[3]))

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 93

Treeview Widget
The result:

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 94

Treeview Widget
 Create a couple of entries that we will use to enter the data that we will insert into our Treeview
and a single button for our command to execute an insert function.

ID = Entry(root, font=("courier", 14, "bold"))


fname = Entry(root, font=("courier", 14, "bold"))
mname = Entry(root, font=("courier", 14, "bold"))
lname = Entry(root, font=("courier", 14, "bold"))

ID.pack(anchor="w")
fname.pack(anchor="w")
mname.pack(anchor="w")
lname.pack(anchor="w")

button1 = Button(root, text="INSERT")


button1.pack(anchor="w")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 95

Treeview Widget
The result:

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 96

Treeview Widget
 To insert data into Treeview, create a method called insert(). For the insert button, use the
command option.

 To retrieve the data entered in our entries, use the get method.

def insert():
var_ID = ID.get()
var_fname = fname.get()
var_mname = mname.get()
var_lname = lname.get()

trv.insert(parent="", index="end", values=(var_ID, var_fname, var_mname, var_lname))

button1 = Button(root, text="INSERT", command=insert)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 97

Treeview Widget
The result:

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 98

Treeview Widget
 height - Height for widget.

trv = ttk.Treeview(root, columns=(0, 1, 2, 3), show="headings", height=5)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 99

Treeview Widget
 To delete data from Treeview, we have three options. We can delete a single row, a selected
row, or all data from the Treeview.

 The first step is to create a button that will send the delete command to a function.

 Create a function called, "delete_one" and inside this function we will use the selection and
delete method for our Treeview.

button2 = Button(root, text="DELETE ONE", command=delete_one)


button2.pack(anchor="w")

def delete_one():
data = trv.selection()[0]
trv.delete(data)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 100

Treeview Widget
Python Tkinter Treeview Selection:

 Selection in Python Tkinter Treeview returns the tuple of selected items.

 Selection method returns the row index of selected items in Treeview.

 It can return more than one indexes at a time in a tuple format.

 Selection is useful is many ways, the value of selection can be stored in a variable and then
using if-else it can be put to condition.

 After knowing the row, items of that row can be accessed or altered by providing then index
number.

 example: row[3], row[1], row[2]

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 101

Treeview Widget
 To delete a selected rows in Treeview, create a function called, "delete_selected" and inside
this function we will use for loop, selection, and delete method for our Treeview.

button3 = Button(root, text="DELETE SELECTED DATA", command=delete_selected)


button3.pack(anchor="w")

def delete_selected():
data = trv.selection()
for row in data:
trv.delete(row)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 102

Treeview Widget
 To delete all rows in Treeview, create a function called, "delete_all" and inside this function we
will use for loop, selection, and getchildren method for our Treeview.

button4 = Button(root, text="DELETE ALL DATA", command=delete_all)


button4.pack(anchor="w")

def delete_all():
data = trv.get_children()
for row in data:
trv.delete(row)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 103

Treeview Widget
Python Tkinter TreeView Selectmode:

Selectmode controls how the built-in class bindings manage the selection. There are three ways to
do so:

 extended: Allows the user to select multiple items.

 browse: Allows only a single selection of items at a time.

 none: The selection will not be changed, the user will click but nothing will be selected.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 104

Treeview Widget
COMPLETED CODES:

from tkinter import *


from tkinter import ttk
root = Tk()
root.title("This is a title")

#functions
def insert():
var_ID = ID.get()
var_fname = fname.get()
var_mname = mname.get()
var_lname = lname.get()

trv.insert(parent="", index="end", values=(var_ID, var_fname, var_mname, var_lname))

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 105

Treeview Widget
def delete_one():
data = trv.selection()[0]
trv.delete(data)

def delete_selected():
data = trv.selection()
for row in data:
trv.delete(row)

def delete_all():
data = trv.get_children()
for row in data:
trv.delete(row)

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 106

Treeview Widget
trv = ttk.Treeview(root, columns=(0, 1, 2, 3), show="headings", height=5, selectmode="extended")
trv.pack()

trv.heading(0, text="ID", anchor="w")


trv.heading(1, text="FIRST NAME", anchor="w")
trv.heading(2, text="MIDDLE NAME", anchor="w")
trv.heading(3, text="LAST NAME", anchor="w")

trv.insert(parent="", index="end", values=(1, "Oldarico", "Balagon", "Pigon"))

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 107

Treeview Widget
records = [
[2, "Danica Karen", "Obra", "Talon"],
[3, "Kairi", "Ygnacio ", "Rayosdelsol"],
[4, "Setsuna", "Dogie", "Ignacio"],
[5, "Manjean" ,"Faduga", "Faldas"]
]

for row in records:


trv.insert(parent="", index="end", values=(row[0], row[1], row[2], row[3]))

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 108

Treeview Widget
ID = Entry(root, font=("courier", 14, "bold"))
fname = Entry(root, font=("courier", 14, "bold"))
mname = Entry(root, font=("courier", 14, "bold"))
lname = Entry(root, font=("courier", 14, "bold"))

ID.pack(anchor="w")
fname.pack(anchor="w")
mname.pack(anchor="w")
lname.pack(anchor="w")

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 109

Treeview Widget
button1 = Button(root, text="INSERT", command=insert)
button1.pack(anchor="w")

button2 = Button(root, text="DELETE ONE", command=delete_one)


button2.pack(anchor="w")

button3 = Button(root, text="DELETE SELECTED DATA", command=delete_selected)


button3.pack(anchor="w")

button4 = Button(root, text="DELETE ALL DATA", command=delete_all)


button4.pack(anchor="w")

root.geometry("800x500")
root.mainloop()

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 110

Quiz 3
Directions:
 Your work should be submitted as a recorded video.
 Pass it on or before September 9th.
 100 pts

Create a program that inserts your name, year, and section and displays them on Treeview; when
you enter the data, the labels should be updated on every attempted insert. Your program should
also be able to delete data from Treeview.

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 111

Quiz 3
SAMPLE OUTPUT:

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon
IPT 2 112

References
 https://www.tutorialspoint.com/python/index.htm
 https://www.tutorialspoint.com/python/python_gui_programming.htm
 https://www.w3schools.com/python/
 https://pythonguides.com/python-gui-programming/

Touching Hearts. Renewing Minds. Transforming Lives. PREPARED BY: Oldarico Pigon

You might also like