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

4th module python

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

4th module python

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

Unit IV: Connecting to Database and GUI Programming

Python MySQL

Python MySQL Connector is a Python driver that helps to integrate Python and
MySQL. This Python MySQL library allows the conversion between Python and MySQL data
types. MySQL Connector API is implemented using pure Python and does not require any third-
party library.
Installation

To install the Python-mysql-connector module, one must have Python and PIP,
preinstalled on their system. If Python and pip are already installed type the below command in
the terminal.
pip3 install mysql-connector-python
Connecting to MySQL Server
We can connect to the MySQL server using the connect() method.
# importing required libraries
import mysql.connector
dataBase = mysql.connector.connect(host ="localhost",user ="user",passwd ="password")
print(dataBase)

# Disconnecting from the server


dataBase.close()

Creating Database
After connecting to the MySQL server let’s see how to create a MySQL database using
Python. For this, we will first create a cursor() object and will then pass the SQL command as a
string to the execute() method. The SQL command to create a database is –

CREATE DATABASE DATABASE_NAME


Example: Creating MySQL database with Python
# importing required libraries
import mysql.connector
dataBase = mysql.connector.connect(host ="localhost",user ="user",passwd ="password")
# preparing a cursor object
cursorObject = dataBase.cursor()
# creating database
cursorObject.execute("CREATE DATABASE gfg")
Creating Tables

1
For creating tables we will follow the similar approach of writing the SQL commands as
strings and then passing it to the execute() method of the cursor object. SQL command for
creating a table is –
CREATE TABLE(
column_name_1 column_Data_type,
column_name_2 column_Data_type,
:
:
column_name_n column_Data_type
);
Example: Creating MySQL table using Python

# importing required libraries


import mysql.connector
dataBase = mysql.connector.connect( host ="localhost",user ="user",passwd ="password", database = "gfg")
# preparing a cursor object
cursorObject = dataBase.cursor()
# creating table
studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(20) NOT NULL,
BRANCH VARCHAR(50),
ROLL INT NOT NULL,
SECTION VARCHAR(5),
AGE INT
)"""
# table created
cursorObject.execute(studentRecord)
# disconnecting from server
dataBase.close()

Insert Data into Tables


To insert data into the MySQL table Insert into query is used.
Syntax:

INSERT INTO table_name (column_names) VALUES (data)

Example 1: Inserting Single Row

#importing required libraries

2
import mysql.connector
dataBase = mysql.connector.connect(host ="localhost",user ="user",passwd ="password",database = "gfg")

# preparing a cursor object


cursorObject = dataBase.cursor()

sql = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\


VALUES (%s, %s, %s, %s, %s)"
val = ("Ram", "CSE", "85", "B", "19")

cursorObject.execute(sql, val)
dataBase.commit()

# disconnecting from server


dataBase.close()

Example 2: Inserting Multiple Rows


To insert multiple values at once, executemany() method is used. This method iterates
through the sequence of parameters, passing the current parameter to the execute method.

# importing required libraries


import mysql.connector
dataBase = mysql.connector.connect(host ="localhost", user ="user",passwd ="password",database = "gfg")

# preparing a cursor object


cursorObject = dataBase.cursor()

sql = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\


VALUES (%s, %s, %s, %s, %s)"
val = [("Nikhil", "CSE", "98", "A", "18"),
("Nisha", "CSE", "99", "A", "18"),
("Rohan", "MAE", "43", "B", "20"),
("Amit", "ECE", "24", "A", "21"),
("Anil", "MAE", "45", "B", "20"),
("Megha", "ECE", "55", "A", "22"),
("Sita", "CSE", "95", "A", "19")]

cursorObject.executemany(sql, val)
dataBase.commit()

3
# disconnecting from server
dataBase.close()

Fetching Data
We can use the select query on the MySQL tables in the following ways –
In order to select particular attribute columns from a table, we write the attribute names.
SELECT attr1, attr2 FROM table_name
In order to select all the attribute columns from a table, we use the asterisk ‘*’ symbol.
SELECT * FROM table_name
Example: Select data from MySQL table using Python

# importing required libraries


import mysql.connector
dataBase = mysql.connector.connect(host ="localhost",user ="user", passwd ="password", database = "gfg")

# preparing a cursor object


cursorObject = dataBase.cursor()

query = "SELECT NAME, ROLL FROM STUDENT"


cursorObject.execute(query)
myresult = cursorObject.fetchall()
for x in myresult:
print(x)
# disconnecting from server
dataBase.close()

Where Clause
Where clause is used in MySQL database to filter the data as per the condition required.
You can fetch, delete or update a particular set of data in MySQL database by using where clause.
Syntax:

SELECT column1, column2, …. columnN FROM [TABLE NAME] WHERE [CONDITION];


Example: Where clause in MySQL using Python

# importing required libraries


import mysql.connector
dataBase = mysql.connector.connect(host ="localhost",user ="user",passwd ="password",database = "gfg")
# preparing a cursor object

4
cursorObject = dataBase.cursor()
query = "SELECT * FROM STUDENT where AGE >=20"
cursorObject.execute(query)
myresult = cursorObject.fetchall()
for x in myresult:
print(x)
# disconnecting from server
dataBase.close()

Order By Clause
OrderBy is used to arrange the result set in either ascending or descending order. By
default, it is always in ascending order unless “DESC” is mentioned, which arranges it in
descending order. “ASC” can also be used to explicitly arrange it in ascending order.
Syntax:
SELECT column1, column2
FROM table_name
ORDER BY column_name ASC|DESC;
Example: Order By clause in MySQL using Python

# importing required libraries


import mysql.connector
dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg")

# preparing a cursor object


cursorObject = dataBase.cursor()
query = "SELECT * FROM STUDENT ORDER BY NAME DESC"
cursorObject.execute(query)
myresult = cursorObject.fetchall()
for x in myresult:
print(x)
# disconnecting from server
dataBase.close()

Update Data
The update query is used to change the existing values in a database. By using update a
specific value can be corrected or updated. It only affects the data and not the structure of the
table. The basic advantage provided by this command is that it keeps the table accurate.
Syntax:
UPDATE tablename
SET ="new value"
WHERE ="old value";

5
Example: Update MySQL table using Python

# importing required libraries


import mysql.connector
dataBase = mysql.connector.connect(host ="localhost",user ="user", passwd ="password",database = "gfg")

# preparing a cursor object


cursorObject = dataBase.cursor()

query = "UPDATE STUDENT SET AGE = 23 WHERE Name ='Ram'"


cursorObject.execute(query)
dataBase.commit()

# disconnecting from server


dataBase.close()

Delete Data from Table


We can use the Delete query to delete data from the table in MySQL.
Syntax:
DELETE FROM TABLE_NAME WHERE ATTRIBUTE_NAME = ATTRIBUTE_VALUE
Example: Delete Data from MySQL table using Python

# importing required libraries


import mysql.connector
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)

# preparing a cursor object


cursorObject = dataBase.cursor()

query = "DELETE FROM STUDENT WHERE NAME = 'Ram'"


cursorObject.execute(query)
dataBase.commit()

# disconnecting from server


dataBase.close()

6
Drop Tables
Drop command affects the structure of the table and not data. It is used to delete an
already existing table. For cases where you are not sure if the table to be dropped exists or not
DROP TABLE IF EXISTS command is used. Both cases will be dealt with in the following
examples.
Syntax:
DROP TABLE tablename;
DROP TABLE IF EXISTS tablename;
Example 1: Drop Table in MySQL using Python

# importing required libraries


import mysql.connector
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)

# preparing a cursor object


cursorObject = dataBase.cursor()

query ="DROP TABLE Student;"

cursorObject.execute(query)
dataBase.commit()

# disconnecting from server


dataBase.close()

How to Connect to MySQL Database in Python


Install MySQL connector module
Use the pip command to install MySQL connector Python.
pip install mysql-connector-python
Import MySQL connector module
Import using a import mysql.connector statement so you can use this module’s methods to
communicate with the MySQL database.
Use the connect() method

7
Use the connect() method of the MySQL Connector class with the required arguments to connect
MySQL. It would return a MySQLConnection object if the connection established successfully
Use the cursor() method
Use the cursor() method of a MySQLConnection object to create a cursor object to perform various
SQL operations.
Use the execute() method
The execute() methods run the SQL query and return the result.
Extract result using fetchall()
Use cursor.fetchall() or fetchone() or fetchmany() to read query result.
Close cursor and connection objects
use cursor.close() and connection.close() method to close open connections after your work
completes
Read or Fetch operation methods:
The fetchone() and fetchall() are the methods of Python MySQL connector and they are
used to display data. This connector helps in enabling the Python programs to use MySQL
databases. In the below code, we have used MySQL using Python for writing all the queries and
fetching all the data from the databases.
1. Fetchone(): Fetchone() method is used when there is a need to retrieve only the first row from
the table. The method only returns the first row from the defined table. The method is also used
when we want to use the cursor() method for the iteration. This method increments the position
of the cursor by 1 and after which it returns the next row.
This method cannot be used for the cursor object rather we run a query using a SQL
statement i.e, “SELECT *” that fetches the first row/tuple from the table. After that, we use
fetchone() method on the result variable returned by the “SELECT *” statement. Now the method
fetches the first row from that result.
Syntax:
row = cursor.fetchone()
Steps for using fetchone() in Mysql using Python:
First. import MySQL connector
Now, create a connection with the MySQL connector using connect() method
Next, create a cursor object with the cursor() method
Now create and execute the query using “SELECT *” statement with execute() method to
retrieve the data
Use fetchone() method on the result variable.
print the result
Example:
Suppose, there’s a table named “CUSTOMERS” and want to retrieve only the first row from it
so, we have to run the below code.

8
# Program to display the data
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "yourusername",
password = "yourpass",
database = "yourdatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM CUSTOMERS")
result = mycursor.fetchone()
print(result)

2. Fetchall(): Fetchall() is a method that fetches all the remaining tuples from the last executed
statement from a table (returns a list of tuples). The method only returns the first row from the
defined table and If there are no tuples then it returns an empty list in the output.
This method cannot be used for the cursor object rather we run a query using a SQL
statement i.e, “SELECT *” that fetches all the rows/tuples from the table. After that, we use
fetchall() method on the result variable returned by the “SELECT *” statement.
Syntax:
row = cursor.fetchall()
Steps for using fetchall() in Mysql using Python:
First. import MySQL connector
Now, create a connection with the MySQL connector using connect() method
Next, create a cursor object with the cursor() method
Now create and execute the query using “SELECT *” statement with execute() method to
retrieve the data
Use fetchall() method on the result variable.
print the result using for each loop to display all
Example:
Suppose, there’s a table named “CUSTOMERS” and want to retrieve all rows from it so, we
have to run the below code.

# Program to display the data


import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "yourusername",
password = "yourpass",
database = "yourdatabase"

9
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM CUSTOMERS")

# This SQL statement selects all data from the CUSTOMER table.
result = mycursor.fetchall()

# Printing all records or rows from the table.


# It returns a result set.
for all in result:
print(all)

Performing Database Transactions using Python


Transactions are a mechanism that ensures data consistency. Transactions have the
following four properties −
Atomicity − Either a transaction completes or nothing happens at all.
Consistency − A transaction must start in a consistent state and leave the system in a consistent
state.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Durability − Once a transaction was committed, the effects are persistent, even after a system
failure
Example
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

TKinter:

Introduction to Python Tkinter


Python Tkinter is the standard Graphical User Interface (GUI) that is supported in Python.
When Tkinter is used alongside Python, it results in the creation of GUI very conveniently and
quite fast. The main advantage of using Tkinter is that it has an object-oriented interface. The
success of any application or website depends on how well it interacts with the user, i.e. an

10
attractive graphical interface helps to create a good application. Well, Python Tkinter does that for
us.
Syntax:
The following are the steps for creating a Tkinter application along with the syntax:

First, we need to import the Tkinter module.


Secondly, we need to create a container window.
Then we add any number of widgets to the container window.
Lastly, we apply the event trigger on the widgets.
# Here, we import the Tkinter module
import tkinter
# Here, we create container window object
c = tkinter.Tk()
# widgets that need to be added
# This executes the application until and unless it is stopped
c.mainloop()
Why do we use Python Tkinter?
Python Tkinter is the most preferred package used for creating nice GUIs for applications
as it has a variety of methods like pack(), grid(), and place() for geometry management. It has
standard attributed dimensions, fonts, colors, cursors, anchors, and bitmaps for better GUI.
Moreover, it has a vast array of widgets to choose from and is by far the easiest to use. The
combination of all these features makes Python Tkinter makes it very popular among Python
developers and makes it a favorable tool to use.
Methods of Python Tkinter
The following are the methods used in Python Tkinter for geometry management:-
1. pack()
It places the child widget in blocks before placing it inside the parent widget.
Syntax:
widget.pack(pack_options)
The possible options for pack_options are the following:
expand: It is a Boolean which can either be True or False. When it is set to True, the child widget
expands to fill the parent widget’s full space.
fill: The default value is none. The other values being X (fill only horizontally), Y (fill only
vertically) and both (fill both horizontally and vertically)
side: It determines the side of the parent widget against which the child widget packs against. The
default value is the top. The other values are bottom, left, and right.
Example:
from tkinter import *
root = Tk()

11
label1 = Label(root,text="This is a tutorial about Python Tkinter")
label1.pack(side=TOP,expand=True)
label2 = Label(root,text="Do you wish to learn?",fg="blue")
label2.pack(side=TOP,expand=True)
button1 = Button(root, text="Accept", fg="green",command=root.destroy)
button1.pack(side=LEFT,expand=True)
button2 = Button(root, text="Close", fg="red",command=root.destroy)
button2.pack(side=RIGHT,expand=True)
root.mainloop()

2. grid()
It places the child widget in grids before placing it inside the parent widget.
Syntax:
widget.grid(grid_options)
The possible options for grid_options are the following:
column: It determines the column to put the child widget inside the parent widget. The default
value is 0, which signifies the leftmost column.
columnspan: It determines the number of columns the widget occupies. The default value is 1.
ipadx, ipady: It signifies the horizontal and vertical padding for the child widget inside the parent
widget’s border in terms of pixels.
padx, pady: It signifies the horizontal and vertical padding for the child widget outside the parent
widget’s border in terms of pixels.
row: It signifies the row to put the widget in.
rowspan: It determines the number of rows the widget occupies. The default value being 1.
Example:
from tkinter import *
root = Tk()
for r in range(9):
for c in range(9):
Label(root , text = 'R%s/C%s'%(r,c),
borderwidth = 1).grid(row = r , column = c , rowspan = 1 , columnspan = 1 , padx = 3 ,
pady = 3)
rsoot.mainloop()

3. place()
It organizes the widgets by placing them on a specific position as indicated by the
developer.
12
Syntax:
widget.place(place_options)
The possible options for place_options are the following:
anchor: This determines the exact position of the widget. The values correspond to the different
directions available in the compass. The possible values are N,S,E,W,NE,NW,SE and SW. The
default value is NW which is at the upper left corner.
bordermode: The possible values are inside and outside. The default being inside.
height, width: This indicates the height and weight in pixels.
relheight, relwidth: This indicates the height and width relative to the parent widget’s height and
width. This is a floating-point number between 0.0 and 1.0
relx, rey: This indicates the offset of the child widget relative to the parent widget. It is a floating-
point number between 0.0 and 1.0
x, y: This indicates the vertical and horizontal offset of the child widget in pixel.
Example:
from tkinter import *
root = Tk()
button1 = Button(root, text ="Hello" , fg="blue")
button1.pack(side = TOP)
button1.place(anchor = E , relheight = 0.25 , relwidth = 0.25 , relx = 0.4 , rely = 0.5)
button2 = Button(root, text = "World" , fg = "green")
button2.pack(side = BOTTOM)
button2.place(anchor = W , relheight = 0.25 , relwidth = 0.25 , relx=0.6 , rely= 0.5)
root.mainloop()

Tkinter Widgets
Python Tkinter is a package or inbuilt library that is used for GUI programming. To develop
GUI applications, Tkinter provides widgets that are used to represent in the browser. Tkinter
widgets are eventful and represented in the browser, such as textbox, button, etc. In Python, Tkinter
widgets are standard GUI elements used to handle events through elements like button, frames,
labels, etc. In Python, Tkinter provides a small range of widgets that are used in some basic GUI
programming, and it also allows us to create specialized widgets as custom widgets. Tkinter
widgets usually provide various controls in the GUI applications.
Tkinter in Python provides various ranges of widgets; roughly, Tkinter has 11 different
widgets in it. Tkinter widgets are necessary as they provide GUI application with a different and
attractive look and feel. Let us see some basic and major widgets in detail with an example:
1. Button
The button is a widget that is used for the user to interact with just one click, or a button is
usually used when there is a click event in the GUI applications. The button is used to control

13
behavior which means if we press or click the button, action or event is performed, such as
displaying text or images.
Syntax:
Button (master, option = value)
Parameters:
Master: This argument is used to represent or declare the root or parent window.
Options: There are many different values for options that are provided button widgets such as
activebackground color, activeforeground color, bg, font, image, width, height, command, etc
Example:
import tkinter as tk
r = tk.Tk()
button = tk.Button(r, text='click me', width=25, command=r.destroy)
button.pack()
r.mainloop()
Output:

In the above code, Tkinter must be imported and then declare root window and initialize button
with the text to be displayed on the button as “click me” with button width as “25” and we have
given command as r.destroy, which is used to close the root window.
2. CheckButton
Checkbutton widget is used to display the checkbox without the checkmark and can access
it through the Tkinter variable. This button usually used to store or record status like on or off, true
or false, etc., which means these are also like buttons but used when the user wants to choose
between two different values or status. In this, the user can select more than one checkbox.
Syntax:
CheckButton (master, option = value)
Options can be like the title for giving the title to the widget, activebackground, and
activeforeground for setting back and foreground color, bg for setting up the background color,
command, font, image, etc.
Example:
from tkinter import *
root = Tk()
v1 = IntVar()
Checkbutton(root, text='Python',width =25, variable=v1).grid(row=0, sticky=S)
v2 = IntVar()
Checkbutton(root, text='Unix',width =25, variable=v2).grid(row=1, sticky=S)

14
v3 = IntVar()
Checkbutton(root, text='Perl',width =25, variable=v3).grid(row=2, sticky=S)
mainloop()
Output:

In the above example, we can see in the screenshot “Python”, and “Unix” checkboxes are check
marked. In the above code, we have declared variables as intvar() for each option to access these
checkbuttons.
3. RadioButton
This is also similar to the checkbutton, but this widget is used when the user is given many
different options but is asked to select only one among all these options. The radiobutton widgets
must be associated with the same variable, and each symbolizes a single value.
Syntax:
RadioButton (master, option = values)
Options are the same as for checkbuttons.
Example:
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='male',width =25, variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='female',width =25, variable=v, value=2).pack(anchor=W)
Radiobutton(root, text='others',width =25, variable=v, value=3).pack(anchor=W)
mainloop()
Output:

In the above example, in the screenshot, we can see that only one button can be selected using the
RadioButton widget.
4. MenuButton

15
This button is associated with a menu widget and displays the selected option when the
user clicks on it. MenuButton is part of a dropdown menu that is always present on the window.
Syntax:
MenuButton (master, option = value)
Again the options are the same as that of checkbuttons and radiobuttons.
Example:
from tkinter import *
root = Tk()
root.geometry("300x350")
menubutton = Menubutton(root, text = "File", width = 35)
menubutton.grid()
menubutton.menu = Menu(menubutton)
menubutton["menu"]=menubutton.menu
menubutton.menu.add_checkbutton(label = "New file", variable=IntVar())
menubutton.menu.add_checkbutton(label = "Save", variable = IntVar())
menubutton.menu.add_checkbutton(label = "Save as",variable = IntVar())
menubutton.pack()
root.mainloop()
Output:

In the above example, we can see the output; when you click on “File”, you will get a dropdown
menu as “New file”, “Save”, and “Save as” else “File” is only and always on the window.
5. Entry
This widget is used to provide the user with a single-line text box to enter the string or
sentence. This widget is limited to only entering one line of strings or sentences. If we want to
enter more than one line, then we can use the text widget.
Syntax:

16
Entry (master, option = value)
Options can be either one among this like, bd for border setting, bg for background color setting,
command, height, width, etc.
Example:
from tkinter import *
root = Tk()
root.geometry("300x350")
Label(root, text='Enter the College Name').grid(row=0)
Label(root, text='Enter the Course name').grid(row=1)
e1 = Entry(root)
e2 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop()
Output:

In the above example, we can see the two text boxes for entry, and in the screenshot, we can see
we have “git” and “cse” as the entry value entered.
6. Label
This widget is used to tell us specifically where to place text or images, which helps the
user to know for what the other widget is for. This widget provides a message as to what the widget
will do to the user.
Syntax:
Label (master, option = value)
Options are again the same as for the Entry widget, and there are many different options also.
Example:
from tkinter import *
root = Tk()
root.geometry("300x350")

17
r = Label(root, text='Educba Training',width =35)
r.pack()
root.mainloop()
Output:

Python tkinter canvas


Python Tkinter is a standard package in which canvas is a class that helps someone
create different shapes with the help of a lot of functions available in it. Here, shapes can
be from simple widgets, a text box, to any complex layouts. Tkinter helps in the easy and
powerful building of GUI applications. The flexible attributes like coordinates, colors,
width, etc., help create any item very easily.

Syntax:
Below is the syntax to create any widget:
w = Canvas ( Master, option=value, ... )
Master: “Master” is the parent window, where the widget needs to be imbibed.
Option: “Option” is the various parameter related to the widget used.
Example

import tkinter

top = tkinter.Tk()

Can = tkinter.Canvas(top, bg="red", height=300, width=300)

coord = 100, 100, 300, 200

arc = Can.create_arc(coord, start=0, extent=150, fill="grey")

18
Can.pack()

top.mainloop()

Python TKinter Label

A Python Tkinter Label is a Tkinter widget class that is used to display text or image in the
parent widget. It is a non-interactive widget whose sole purpose is to display any message
to the user
Syntax:
w = Label (master, option, ...)
The following are the parameters of Python Tkinter Label:

 Master: This is the parent widget.


 Options: This represents a list of options that can be used on the parent widget.
These are key-value pairs that are separated by a comma.
Options Used in Python Tkinter Label
Python Tkinter Label is used to specify the container box where we place text or images. It is used
to provide the user with information about the widgets used in the Python application.

The following are the options that can be used in the Python Tkinter Label:

1. anchor: This option helps us control the position of the text when the parent widget has
more space than the text needs. The value of the anchor corresponds to the different options
available in a compass. The default option being CENTER.
2. bg: This signifies the background color that is to be displayed behind the label and the
indicator.
3. bitmap: This is used to display an image in the label
4. bd: This indicates the size of the border around the indicator. The default value is 2 pixels.
5. cursor: This is used to denote the type of cursor, i.e. arrow or dot.
6. font: This signifies the font in which the label is to be displayed.
7. fg: This option helps to set the color of the text when we are displaying text in the label.
When we are displaying bitmap, this option helps us to determine the color of the 1-bits in
the bitmap.
8. height: It determines the vertical dimension of the label.
9. image: It helps us to set an image in the label widget.

19
10. justify: It determines how multiple lines of text would be aligned with respect to each
other. The possible options are LEFT for left-justified, CENTER for center alignment and
RIGHT for right-justified. The default value is CENTER
11. padx: This signifies the extra spaces added to the label’s start and end. The default value
is 1.
12. pady: This signifies the extra spaces added to the top and bottom of the text in the label.
The default value is 1.
13. relief: It determines the appearance of the border around the label. The default value is
FLAT.
14. text: This option is used to display one or more lines of text in a label widget.
15. textvariable: This option also helps us display text in the label widget; the only difference
is the method by which we are showing the text. In the textvariable method, a StringVar
class object is created and then using the set option on that object, we can assign the text.
16. underline: With this option’s help, we can display underline beneath the text in a label.
The underline would start from the 0th element and commence on an nth element. The
default value for underline is -1, which means there is no underline.
17. width: This signifies the width of the label in characters. The label will be sized to fit its
content if this option is not set.
18. wraplength: This helps us to limit the number of characters in each line by mentioning the
value to the desired value. The default value is 0.

Tkinter Text

Tkinter Text display is allowed using text widget that is the text can be displayed and
edited with various styles and attributes using the text widget, also it supports embedded
images and windows, the text documents that is displayed can be either plain text or
formatted text, and it can also be used as a text editor, and the body of the text can be
made up of characters, marks, embedded windows or images.

Syntax:
w = text (master, option,..)
where the master is the parent window, and option is the options list that can be used for the widget,
and options are the pairs of key-value that have commas as a separator.
Tkinter Text Widget
The most commonly used list of options for the widget are:

 bg: This option represents the text widget’s background color, and this is the default value.
 bd: This represents the border width surrounding the text widget. Its default value is two
pixels.

20
 cursor: When the mouse is placed on the text widget, a cursor appears, and that is this
cursor.
 font: This represents the font of the text which is present in the text widget.
 fg: This represents the color of the text present in the text widget. The color can be changed
for regions that are tagged. This is just a default option.
 height: This represents the text widget’s height in lines, and its measure is based on the
font size.
 highlightcolor: This represents the focus highlight color when the focus is in the text
widget.
 highlightthickness: This represents the focus highlight thickness. The default value for
highlight thickness is one. The display of the focus light can be suppressed by setting
highlight thickness as zero.
 relief: This provides the text widget’s three-dimensional appearance by option. The default
value for relief is SUNKEN.
 selectbackground: This represents the background color to be used while displaying the
text that is selected.
 width: This represents the width of the character present in the text widget, and its measure
is based on the font size.
 xscrollcommand: The set() method of the horizontal scrollbar is set to xscroll command
option, which makes the text widget to scroll in the horizontal direction.
 yscrollcommand: The set() method of the vertical scrollbar is set to xscroll command
option, which makes the text widget to scroll in the vertical direction.
 exportselection: The text contained in the text widget is selected and is made a selection
in the window manager by exporting it to the window manager.
 highlightbackground: The focus highlight’s color when the focus is not in the text widget.
 insertbackground: The insertion cursor’s color. The default value for this option is black.
 insertborderwidth: The three-D border’s size surrounding the insertion cursor. The
default value for this option is zero.
 insertofftime: During the insertion cursor’s blink cycle, the number of milliseconds it is
off is inserted off time. The blinking can be suppressed by setting this choice to zero. The
default value for this option is three hundred.
 insertontime: During the insertion cursor’s blink cycle, the number of milliseconds is on
insert on time. The blinking can be suppressed by setting this option to zero. The default
value for this option is six hundred.
 insertwidth: This option represents the insertion cursor’s width. The default value for this
option is two pixels.
 padx: Internally, padding is done to the left and right of the text area, and this option
represents the size of this padding. One pixel is the default value for this option.
 pady: Internally, padding is done above and below of the text area, and this option
represents the size of this padding. The default value for this option is one pixel.

21
 selectborderwidth: This option represents the border width around the text that is selected.
 spacing1: There is excess space that is vertical, which is assigned above each line of text,
and this option represents the amount of that extra vertical space. If there is a line wrap,
there is the addition of space before the first line only. The default value for this option is
zero.
 spacing2: There is excess space that is vertical, which is assigned between displayed lines
of text, and this option represents the amount of that extra vertical space. The default value
for this option is zero.
 spacing3: There is excess space that is vertical, which is assigned below each line of text,
and this option represents the amount of that extra vertical space. If there is a line wrap,
there is an addition of space after the last line only. The default value for this option is zero.
 state: Keyboard and mouse events get a response from text widgets, and this response is
available when the state is set to the value NORMAL. There is no response if the state
value is set to DISABLED, and the contents cannot be modified programmatically.
 tabs: This option controls the position of the text based on the tab characters.
 wrap: If the lines to be displayed are too wide, then they are controlled by this option. If
this option is set to WRAP, then the line is broken after the last word fits. If this option is
set to CHAR, then the line is broken at any character.
Methods of Tkinter Text
There are several methods that can be implemented on text objects, they are:

 delete(startindex, [,endindex]): The indices in the range (startindex, [,endindex]) are


deleted using this option. The specific character having the first index is deleted if the
second argument is omitted.
 get(startindex, [,endindex]): The range of text or specific character is returned.
 index(index): Based on the given index, which is passed as an argument, the index’s
absolute value is returned.
 insert(index, [,string]…): The strings passed as the second argument are inserted at the
position specified by the index passed as the first argument.
 see(index): The text located at the position specified by the index argument is visible; this
method returns true.
Text widgets support two helper structures. They are:

 marks: In each text, we use marks if we want to highlight positions between two
characters.
o index(mark): The mark specifies the line, column that must be returned.
o mark_gravity(mark,[,gravity]): The gravity of the mark specified as the first
argument is returned. The gravity for the mark specified as the first argument is set
if the second argument is specified.
o mark_names(): All of the text widget’s marks is returned.

22
o mark_set(mark,index): The specified mark as the first argument is informed
about the new position.
o mark_unset(mark): The specified mark as the first argument is removed from the
text widget.

 Tags: The text regions are associated with tags given by tags, which makes the
modification of the display settings of the text areas easier. Event callbacks can be bind to
specific areas of text using tags.
o tag_add(tagname, startindex[,endindex]…): The start index’s position is tagged
using this method or a range of positions defined by the start index and end index
are tagged using this method.
o tag_config: The properties of the tag are configured using this option like justify,
tabs, underline, etc.
o tag_delete(tagname): A given tag can be deleted and removed using this method.
o tag_remove(tagname,[startindex[.endindex]]..): A given tag is removed from
the area where it is present without deletion of the definition of the actual tag after
application of this method.

Tkinter scrollbar
Tkinter Scrollbar widget basically provides the slide controller, which is used to implement the
vertical scrolling widgets like the Listbox, Canvas, and the Text. Using the Tkinter scrollbar
widget, one can also try creating the horizontal scrollbar on the entry widgets. Tkinter scrollbar is
used to roll through the content to see the whole content vertically when the scrollbar is set to
vertical. A horizontal scrollbar is used to scroll over the content horizontally. Scrollbar() syntax
will be used to get a scrollbar with the attributes: master and the option/options.

Syntax:
w=scrollbar( master, option/options, … )
Attributes:

 Master: This master attribute of the Tkinter scrollbar represents only the parent window
 Option/options: The option/options attribute of the Tkinter scrollbar will have the list of
option which are commonly used for the scrollbar widget. These option/options mainly are
used as the key-value pairs, which are separated by the commas.
Tkinter Scrollbar Widget
The most commonly used list of options for the widget are:

23
 activebackground: The “activebackground” option of the Tkinter scrollbar is used to color
the slider/scrollbar/arrowhead/ arrowheads/cursor symbols when the mouse/cursor point is
on the scrollbar/slider.
 Bg: The “bg” option of the Tkinter scrollbar is very much helpful in changing the
background of the scroll bar/arrowheads/cursor points when the mouse/cursor point is
actually not on the scroll bar/slider.
 bd: The “bd” option of the Tkinter scrollbar is used to set the width of the 3d border around
the whole trough’s perimeter and also the 3d effects’ width on the slider and the mouse
point/arrowhead/cursor point. By default, there will be no borders around/beside at every
corner of the trough. Along with that border which is having 2 pixels that are all around
the slider and the arrowheads/cursor points.
 command: The “command” option of the Tkinter scrollbar/slider is the procedure that is
also to be called every time when the scrollbar/slider is moved as needed.
 cursor: The “cursor” option of the Tkinter scrollbar widget is to make the cursor to appear
when the scrollbar is below the mouse/the cursor point.
 elementborderwidth: The “elementborderwidth” option of the Tkinter scrollbar widget
helps to adjust the border width around the slider and the arrowheads/cursor points. By
default, the elementborderwidth is with the value “1”. You can add any border width using
the elementborderwidth option as we needed/required.
 highlightbackground: The “highlightbackground” option of the Tkinter scrollbar widget
helps highlight color’s whenever the scrollbar/slider doesn’t have any focus.
 highlightcolor: The”highlightcolor” option of the Tkinter scrollbar widget is used for the
focus color of the highlight when the mouse point/scrollbar/slider has the focus.
 highlightthickness: The “highlightthickness” option of the scrollbar widget is useful for
setting the highlight’s thickness, but by default, the highlight thickness value is set to 1.
You can set to the value 0 in order to suppress the focus highlight’s display.
 jump: The “jump” option of the Tkinter scrolling widget controls what to happen when
the user drag/drags the slider. By default, 0 value of the jump option causes the callback
command for every small slider drag. If the jump option value is set to value 1, the callback
is not called if the user doesn’t release the mouse/cursor button.
 orient: The “orient” option helps to set the orientation as horizontal/vertical. It is like
orient=HORIZONTAL OR orient =VERTICAL .
 repeatDelay: The “repeatDelay” option helps us to control how much time button 1 is to
be held down in the trough before slider moves in the specific direction repeatedly. By
default, the repeating delay (repeatdelay=300) is 300, and the units are of milliseconds.
 repeatInterval: The “repeatInterval” option is for repeating the interval of the slider.
 takefocus: The “takefocus” option is for tabbing the focus through the scrollbar widget,
but one can set it with the value 0 if you don’t want this feature/behavior.
 troughcolor: The “troughcolor” option is for changing the color of the trough.

24
 width: The “width” option is to set the scrollbar/slider’s width ( x dimension is for vertical
and y dimension is for horizontal). By default the width value is 16 (width=16).
Methods of Tkinter Scrollbar
These are the methods that are used with the Tkinter Scrollbar Objects:

 get(): The get() method returns 2 numbers, a and b, which is used to describe the slider’s
current position. The get() value gives the exact position of the edge of the slider (left or
right) and also for the vertical and the horizontal scrollbars, respectively, but the b’s value
is for the right edge’s or the bottom edge’s position.
 set ( first1, last1 ): The set() method is to connect the scroll bar/ slider to another widget
“w”. set w’s yscrollcommand or the yscrollcommand to slider/scrollbar’s set () method.
These arguments have the same/similar meaning as all the values which is returned by the
get() method.
 Pack(): This method is useful to set the alignment of the slider/sidebar.

TKinter Listbox
Tkinter Listbox widget is used to display a list of items of which all are text items having the same
font and color. The user can choose more than one item from the list to be displayed depending on
the widget’s configuration. The Listbox is initially empty when it is created and requires insertion
of more than one lines of text which can be done using the insert method for which an index and
string must be given as arguments of which index is the item number in the list and string is the
text item to be displayed
syntax:

w = Listbox(master, option,..)

The master represents the parent window, and the option is the list of options that can be used for
the widget, and options are the key-value pairs separated by commas.

Tkinter Listbox Widget


The most commonly used list of options for the widget are:

 bg: Behind the label and indicator, the normal background color is displayed.

 bd: This represents the border size around the indicator. Its default value is two pixels.

 cursor: When the mouse is moved over the Listbox, a cursor appears, and that is this
cursor.

 font: This represents the font of the text present in the Listbox.

25
 fg: This represents the color of the text in the Listbox.

 height: This represents the number of lines in the Listbox. The default value for the number
of lines is ten.

 highlightcolor: This represents the focus highlight color when the focus is in the widget.

 highlightthickness: This represents the focus highlight thickness.

 relief: The border shading effects is selected as three dimensional by relief. The default
value for relief is SUNKEN.

 selectbackground: This represents the background color to be used while displaying the
text that is selected.

 selectmode: This specifies the number of items that can be chosen, and the effect of mouse
drag on the selection

 Browse: This is the default setting. One line from the Listbox can be selected. If an item
is clicked and dragged to some other line, the chosen line goes along with the mouse.

 Single: Only one line can be selected, and the mouse cannot be dragged; wherever the
button one is clicked, that corresponding line is chosen.

 Multiple: The number of lines that can be selected at once is not fixed. Selection can be
determined by clicking on any line and its toggling.

 Extended: The number of adjacent groups of lines that can be selected at once is not fixed
and is selected by dragging the last line from clicking on the 1st line.

 width: This represents the width of the character present in the widget. The default value
of the widget is twenty.

 xscrollcommand: The horizontal scrollbar linked to the Listbox widget allows the user to
horizontally scroll the Listbox.
 yscrollcommand: The vertical scrollbar linked to the Listbox widget allows the user to
vertically scroll Listbox.

There are several methods that can be implemented on Listbox objects, they are:

 activate(index): The line which is specified by the index passed as an argument is selected.

26
 curselection(): The selected elements line numbers starting from zero is put into a tuple
and is returned by the curselection() method. An empty tuple is returned if there is no
selection.

 delete(first, last=None): The indices in the range [first, last] are deleted using this option.
The single line having the first index is deleted if the second argument is omitted.

 get(first, last=none): The lines consisting of the text whose indices from the first line to
the last line is contained in a tuple and is returned. The text of the line similar to the first
line is returned if the first argument is omitted.

 index(i): The portion of the Listbox that is visible is positioned in such a way that the top
of the widget consists of a line with index i.

 insert(index, *elements): More than one lines in inserted into the Listbox keeping the line
marked by the index above all the lines. If new lines are to be added to the listbox’s end,
END must be used as the first argument.

 nearest(y): The index of the line that is visible and which is nearest to the y coordinate
Listbox widget’s y relative is returned.

 see(index): The place of the Listbox is adjusted so that the index referred lines are visible.

 size(): The count of lines in the Listbox is returned.

 xview(): The horizontal scrollbar’s command option is set to the xview() method to make
the Listbox horizontally scrollable.

 xview_moveto(fraction): When the Listbox is scrolled, the leftmost fraction of the longest
line’s width in the listbox is present outside the left side of the Listbox. The range of the
fraction is [0,1].

 xview_scroll(number, what): This method is used to horizontally scroll the Listbox. What
argument uses either UNITS, which scrolls with respect to characters or PAGES, which
scrolls with respect to pages by the listbox’s width. The number of times to be scrolled is
told by the number argument.

 yview(): The command option of the vertical scrollbar is set to yview() method to make
the Listbox vertically scrollable.

27
 yview_moveto(fraction): When the Listbox is scrolled, the top fraction of the longest
line’s width in the Listbox is present outside the left side of the Listbox. The range of the
fraction is [0,1].

 yview_scroll(number, what): This method is used to vertically scroll the Listbox. What
argument uses either UNITS, which scrolls by characters or PAGES, which scrolls by
pages by the listbox’s height. How many to scroll is told by the number argument.

TKinter checkbutton

The Tkinter Checkbutton (GUI – Graphical User Interface), which contains the images or
the text, is helpful in order to track the options/choices which are provided to the
application, and it also helps in order to implement the off/on selections by providing
many/multiple choices to the user/users in order to choose one choice/option among all of
them.
Syntax:
W = checkbutton ( master, option/options = value/values, …. )
Attributes:
 Master: This master term will represent the parent window.
 Option/Options: This option/options terms will list the most commonly used options for
the widget. All the options which are used as the value/key-value pairs which are separated
by the commas.
List of Options with Description
Given below are list of options with description.
1. activebackground: This will help with the background color when the cursor is on the
checkbutton.
2. activeforeground: This will help to get the foreground color when the cursor is on the
checkbutton.
3. bg: This option of the Tkinter checkbutton will help get the normal background color displayed
behind the indicator and the label.
4. bitmap: This option will help in order to display the monochrome image on the checkbutton.
5. bd: The bd option of the Tkinter checkbutton will help to get the size of the border, which is
around the indicator, which is by default of 2 pixels size.
6. command: The “command” option of the Tkinter checkbutton will help with the procedure
used to be called each and every time the user wills to change the checkbutton state.
7. cursor: The “cursor” option will help you to place a name to the cursor ( for the dot/arrow etc..).
After this, you can get a different pattern like name/other when the mouse cursor is on the
checkbutton.

28
8. disabledforeground: The “disabledforeground” option will help us get the foreground color
used to render the disabled checkbutton text. By default, the default foreground color is the stippled
version.
9. font: The “font” option helps us to get the text using the option.
10. fg: The “fg” option is the color used to render the text.
11. height: The “height” option of the Tkinter checkbutton will help to get many text lines on the
checkbutton, and by default, it will be the value as “1”.
12. highlightcolor: The “highlightcolor” option of the Tkinter option will help get the color for
the highlight focus when the check button focuses on it.
13. image: The “image” option helps to get a graphic image display on the button.
14. justify: The “justify” option of the Tkinter checkbutton will help us only if the text contains
many/multiple lines; this is the option that only controls how the text will be justified like left,
right or the center.
15. offvalue: The “Offvalue” option will help make the control variable associated with the
checkbutton value as 0 normally. You can also set it to an alternative value to the off state with the
setting value’s help.
16. onvalue: The “onvalue” option of the Tkinter checkbutton will set the control variable value,
which is associated with the checkbutton as 1 by default. Like the Offvalue option, here also you
can set the value to the alternate value as you wish by passing the value to the onvalue.
17. padx: The “padx” option will help us to know how much space is needed to the right and the
left of the checkbutton. By default, the size of the space will be only 1 pixel.
18. pady: The “pady” option will help know how much space is needed above and below the
checkbutton and text. By default, the size of the space value will be only 1 pixel.
19. relief: The “relief” option is with the default value relief=FLAT , checkbutton couldn’t stand
out from its background. You can set this option to all of the other styles.
20. selectcolor: The “selectcolor” option will help to set the color of the checkbutton, but by
default, it will be red (selectcolor = “red” ).
21. selectimage: The “selectimage” option of the Tkinter checkbutton will help to set an image to
the checkbutton. The image will appear on the checkbutton if it is set by using the “selectimage”
option.
22 state: The “state” option is by default state = normal, but one can use it as state = disabled to
grey out of control and make it unresponsive. If the cursor is over to the checkbutton, then the state
is active.
23. text: The “text” option will help get the label displayed next to the checkbutton. You can
display many/multiple lines of text using the “\n” term.
24 underline: The “underline” option is with the default value as -1, but most of all, the characters
will not be underlined. By setting the option of the index of the character in text (from the value 0
as starting) to that character’s underline.

29
25. variable: This option helps to track the checkbutton’s current state. Usually, the variable will
be an IntVar, 0 is for the cleared, and 1 means set, but you can see the onvalue and the off value
options above.
26. width: This option, by default, the checkbutton width is determined by the displayed
image/text size. You can also have an option to set the numbers of characters & then the
checkbutton will have a lot of space for many characters possible.
27. wraplength: The “wraplength” option has lines that are wrapped. One can easily set this option
to many character numbers, and all the lines will be broken into many pieces which are no longer
a number.
Methods
There are only a few methods that are called with the checkbuttons of Tkinter. Check out those
below:
 Deselect(): It is used to turn off the Tkinter checkbutton in the program.
 Flash(): It is used to flash the checkbutton, which is between the normal and the active
colors.
 Invoke(): It is used for method invoking which is associated with the Tkinter checkbutton
 Select(): It helps to turn on the Tkinter checkbutton implementation in the program.
 Toggle(): It is helpful to toggle between different types of checkbuttons
TKinter Menu
Tkinter Menu is a widget that helps in creating a set of action items that are going to be used in
the application. Tkinter is a standard package in python. To create multiple choices in terms of
symbols and text, the menu helps with that. The moment any of the choices is clicked or touched,
an action is activated, which could be in terms of any operation like opening a file, saving a file,
etc.
There is two popular variety of Menu, we will discuss here:

1. Pull-down
2. Pop-up
Syntax:
Below shown is the syntax to create any Menu widget:
w = Menu ( master, option, ... )
Master: The parent window, where the widget needs to be imbibed.
Option: The various parameter related to the widget used.
Menu Methods with Examples
The different methods are given below:
1. Pull-down Menu
Let’s discuss the first type of menu, i.e. Pulldown Menu.
Code:

from tkinter import *

30
Master = Tk()

variable = StringVar(Master)

variable.set("Open") # default value

wi = OptionMenu(Master, variable, "Open", "save", "save as")

wi.pack()
mainloop()
Output:

As one can see, “OptionMenu” is used from the Tkinter package to implement a pull-down menu.
Tk helps in the creation of the top-level window. Here “OptionMenu” will pop up with a button.
To which, we have set a default value of “Open”. Rest other values “save” & “save as” can be
selected from the dropdown. If further someone wants action to be associated with it, one can use
the .get() function to accomplish it.

TKinter Menubutton
The following article provides an outline of Tkinter Menubutton. In python, the Tkinter
menu button is defined as a menu button that always is a part of a drop-down menu on the
screen which stays all the time, and the menu button is associated with a menu widget that
provides different options to select from the application when the user clicks on the menu.
It is used to create different types of menu’s in applications based on the requirement. It
provides options to the user to select from the menu with all the options available in the
application is called the Tkinter menu button. A menu button is generally used to create
top-level menus in the application
Syntax of Menu Button with Options
Following are the syntax and menu button with options:

Syntax:

31
w = tk.menu button(parent, option, ...)

Where the parent is the root window or parent window.

Where the option is a list of commonly used options in the menu widget, which can be used as
key-value pairs.

List of Options:

 activebackground: This option gives the background color when the user places the
mouse over the menu button.
 activeforeground: This option gives the foreground color when a user places the mouse
over the menu button.
 anchor: This option sets the position of the text in the application based on the options set
by the user by default, it will be in the center(anchor = tk.CENTER), and by using(anchor
=tk.W) will place the text-centered against the left side.
 Background or bg: This option gives the original background when the mouse is not over
the user’s menu button.
 Cursor: This option gives the cursor when we place the mouse on the menu button.
 compound: This option will specify where the images should appear relative to the text
with different positions as TOP, LEFT, RIGHT, BOTTOM, CENTER, and NONE (in this
case, the text won’t display only graphics will).
 Direction: This option will set the menu’s position or direction where it needs to display
on the screen. We have three options LEFT, RIGHT, and above of menu button.
 Disabledforeground: This option will show the foreground color on the menu button
when it is disabled.
 Forground or fg: This option will show the original foreground color when the mouse is
not over the menu button.
 Font: This option specifies the type of font used to display the text on the screen.
 height: This option defines the height of the menu button inline with text, not pixels; by
default, it will fit its content.
 Highlightbackground: This option highlights the background color, which is in focus
when the cursor is not active.
 Highlightcolor: These options show the color which is in focus when the menu button
widget has focus.
 Highlightthickness: This option highlights the focus thickness.
 Image: This option displays images when image objects set with this.
 Justify: This option controls the text to display when it is not in the menu button.
 Menu: This option will associate with the menu button to provide different choices by
setting this option to the menu object.

32
 Padx: This option tells the space that needs to leave towards the menu button’s left and
right.
 Pady: This option tells the space you need to leave above and below the menu button.
 Relief: This option enables 3d-effects to the menu button.
 State: This option provides an option to disable the menu button or unresponsive.
 Takefocus: This option enables to add focus using a keyboard by setting take focus=True.
 Text: This option will tell the menu button to display the text string.
 Textvariable: This option enables us to associate a string variable to the menu button.
 Underline: This option enables to underline any of the characters’ text on the menu button.
 Width: This option enables us to set the width of the menu button based on characters; by
default, it will fit its contents.
 Wraplength: This option enables to wrap lines by setting this option to a number of
characters; all lines will be broken into the pieces exactly as the number.

33

You might also like