Tkinter
Tkinter
to interact with the computers. They perform different tasks in the desktops, laptops
and other electronic devices.
GUI apps like Text-Editors create, read, update and delete different types of
files.
Apps like Sudoku, Chess and Solitaire are games which you can play.
GUI apps like Google Chrome, Firefox and Microsoft Edge browse through
the Internet.
They are some different types of GUI apps which we daily use on the laptops or
desktops.
Python Libraries To Create Graphical User Interfaces:
Python has a plethora of libraries and these 4 stands out mainly when it comes to
GUI. There are as follows:
Kivy
Python QT
wxPython
Tkinter
Among all of these, Tkinter is the first choice for a LOT of learners and developers
just because of how simple and easy it is.
Tkinter is actually an inbuilt Python module used to create simple GUI apps. It is the
most commonly used module for GUI apps in the Python.
Fundamentals Of Tkinter
Consider the following diagram, it shows how an application actually executes in
Tkinter:
To start out with, we first import the Tkinter model. Followed by that, we create the
main window. It is in this window that we are performing operations and displaying
visuals and everything basically. Later, we add the widgets and lastly we enter the
main event loop.
If you noticed, there are 2 keywords here that you might not know at this point.
These are the 2 keywords:
Widgets
Main Event Loop
An event loop is basically telling the code to keep displaying the window until we
manually close it. It runs in an infinite loop in the back-end.
Check out the following code for better clarity:
1 import tkinter
3 window = tkinter.Tk()
4
5 # to rename the title of the window window.title("GUI")
10
11 window.mainloop()
As you can see, we are importing the Tkinter package and defining a window.
Followed by that, we are giving a window title which is shown on the title tab
whenever you open an application.
For example, Microsoft Word is shown on the title tab when you open a word
application, Similarly here we call it GUI. We can call it anything we want based on
the requirement.
Lastly, we have a label. A label is nothing but what output needs to be shown on the
window. In this case as you can already see, it is hello world.
Check out the output for the above code:
Next up on this Tkinter tutorial blog, let us look at the massive range of widgets
offered by Tkinter.
Tkinter Widgets
Widgets are something like elements in the HTML. You will find different types
of widgets to the different types of elements in the Tkinter.
Let’s see the brief introduction to all of these widgets in the Tkinter.
Check out this diagram for the list of the majorly used Tkinter widgets:
Label Widget:
Labels are used to create texts and images and all of that but it is important to note
that it has to be a single line definition only.
Here’s the code snippet:
1 l1 = Label (window, text="edureka!“ font=("Arial Bold", 50))
3 window.geometry('350x200')
Button Widget:
The button widget is very similar to the label widget. We create a variable and use
the widget syntax to define what the button has to say.
Check out the below code snippet:
1 bt = Button (window, text="Enter")
Here, we used a function called as the grid function which is used to set the position
of the button on our window.
The output of the code is as follows:
We can also change the foreground for a button or any other widget as well. We will
be using the parameter FG as shown in the code. Similarly, the background colour
can be changed as well using the BG property.
Check out the code:
1 bt = Button (window, text="Enter", bg="orange", fg="red")
Output:
As per the output we got, our foreground is the text which is red color as defined and
the background is orange as we’ve set it using the bg parameter.
So at this point, we have a clickable button. Well, what happens when we actually go
ahead and click it?
Check out this snippet:
1 def clicked():
So we call this the click event. We need to write the functionality as to what should
happen when we click the button or in other terms when the click event is fired.
For that purpose we have a function called clicked, we are displaying a text message
saying button was clicked.
We will need to add a parameter called command in the button definition as shown.
Pretty easy, right?
The next widget we will check on this Tkinter tutorial blog is the entry widget.
Entry Widget:
What is an entry widget used for?
It is used to create input fields in the GUI to take in textual input.
Check out the example code shown below:
1 txt = Entry(window,width=10)
3 txt.grid(column=1, row=0)
4
def clicked():
5
6
res = "Welcome to " + txt.get()
7
8
l1.configure(text= res)
9
10
bt = Button (window, text=“Enter”, command=clicked)
11
Here, we are creating a textbox using the Tkinter entry class. The grid tells the code
where we want the widget on the window.
What should happen when the button is clicked?
Well, we have a message that says ‘Welcome to’ and later whatever is input into the
text area will be concatenated along with this and printed.
Check out the output. We’ve typed Python Training and so it displays welcome to
python training.
Output:
All these widgets are really simple and more than that they always come in handy as
well.
The next widget we will check on this Tkinter tutorial blog is the combobox widget.
Combobox Widget
Can you take a quick guess on what a combobox widget is?
Well, it is just a drop-down menu with certain options.
Here’s the code snippet:
1 from tkinter.ttk import *
2 combo = Combobox(window)
4 combo.current(3)
combo.grid(column=0, row=0)
5
So check out that there are no other parameters for the combobox definition apart
from the window. And in the next line, we have defined certain values such numbers
ranging from 1 to 5 and next, we have text. 1 to 5 were numeric inputs but we can
have a textual input too.
It is defined using double quotes and we later will set the selected input. Followed by
that, we have the grid function to place the widget on the window.
So we have the drop-down menu and it displays all that we’ve defined in the code.
Here is the output for the code:
2 chk_state.set (True)
4 chk.grid(column=0, row=0)
Check out the above output. So we have a really simple checkbutton widget with a
certain text.
So what other easy widgets like these are available?
The next widget we will check on this Tkinter tutorial blog is the radio button widget.
Radio Button Widget:
The radio button widget is quite popular and I can give you a guarantee that you
have seen and used this widget before.
We will use the radiobutton class to add the widget.
Take a look at the code:
1 rad1 = Radiobutton(window, text=Python', value=1)
2 rad2 = Radiobutton(window, text=Java', value=2)
4 rad1.grid(column=0, row=0)
5 rad2.grid(column=1, row=0)
rad3.grid(column=2, row=0)
6
Here, we have the value parameters to be different. 1,2 and 3. However, if they are
same, it will lead to conflict and there will be an error. So it is to be noted that a
unique value is used to address the radio buttons.
The value should be unique but the textual data can be the same, however. Here we
have considered Python, Java, and Scala. It can be whatever you want it to be
based on the requirements.
Data Science Training
5(86329)
5(23531)
5(10313)
DATA SCIENCE CERTIFICATION COURSE USING R
Data Science Certification Course using R
Reviews
5(37663)
5(24060)
5(5691)
5(4589)
5(1260)
Next
Similarly, the grid function used to place the widget on the window.
Output:
From the above output, do note that unlike a checkbutton where you can try
selecting multiple, here in case of radio button you can only select one at a time.
The next widget we will check on this Tkinter tutorial blog is the scrolled text widget.
Scrolled Text Widget:
Another nice widget we have is the scrolled text widget. This can be added using the
scrolled text class.
Code:
1 from tkinter import scrolledtext
One thing you must note here which is very important is that you need to specify the
width and the height of the scrolled text widget. Well if we do not specify the same,
the entire window is filled up.
You can set the scrolled text content by using the insert method. The syntax is pretty
simple. We need to use txt.insert with the message as a parameter.
Output:
The next widget we will check on this Tkinter tutorial blog is the message box widget.
Message Box Widget:
Let us quickly walk through this simple widget. We are using the messagebox library
here as well.
Code:
1 from tkinter import messagebox
Importing the library and displaying the message. But we need to define the
message title and the message content here.
See, this is where things get interesting. Look at the snippet below:
1 def clicked():
Here we have made use of two of the widgets we learnt. We are using a button click
to show a message box for us.
Here’s the output:
We have 3 parameters – from, to and width. From – tells the start and the default
value of the range and to – gives us the upper threshold of the range.
Width is basically to set the size of the widget to 5 character spaces. But since are
doing 0 to 100, 3 is sufficient for us but I have gone ahead and put 5 just so it looks
well placed.
You can put whatever you want here and it’s valid but make sure it is more than what
the range can offer.
Output:
And that’s a wrap to the majorly used widgets in Tkinter.
Next up on this Tkinter tutorial blog, we need to check out geometry management.
Geometry Management
All widgets in the Tkinter will have some geometry measurements. These
measurements give you to organize the widgets and their parent frames, windows
and so on.
Tkinter has the following three Geometry Manager classes.
pack():- It organizes the widgets in the block, which mean it occupies the entire
available width. It’s a standard method to show the widgets in the window.
grid():- It organizes the widgets in table-like structure.
place():- It places the widgets at a specific position you want.
We already looked at the grid in almost all of the previous codes. If you have any
doubts, head to the comment section and leave a comment, let’s interact there.
Next up on this Tkinter tutorial blog, we need to check out how we can organize
layouts and widgets.
2 window = tkinter.Tk()
window.title("GUI")
3
# creating 2 frames TOP and BOTTOM
4
top_frame = tkinter.Frame(window).pack()
5
bottom_frame = tkinter.Frame(window).pack(side = "bottom")
6
# now, create some widgets in the top_frame and bottom_frame
Above code produces the following window, if you didn’t change the above code.
window = tkinter.Tk()
1
window.title("GUI")
2
# creating 2 text labels and input labels
3
tkinter.Label(window, text = "Username").grid(row = 0) # this is
4 placed in 0 0
window.mainloop()
Next up on this Tkinter tutorial blog, we need to check out a concept called binding
functions.
Binding Functions
Calling functions whenever an event occurs refers to a binding function.
In the below example, when you click the button, it calls a function called say_hi.
Function say_hi creates a new label with the text Hi.
1 import tkinter
2 window = tkinter.Tk()
3 window.title("GUI")
5 def say_hi():
6
tkinter.Label(window, text = "Hi").pack()
7
tkinter.Button(window, text = "Click Me!", command = say_hi).pack()
8 # 'command' is executed when you click the button
9 # in this above case we're calling the function 'say_hi'.
10 window.mainloop()
2 window = tkinter.Tk()
window.title("GUI")
3
# creating a function with an arguments 'event'
4
def say_hi(event): # you can rename 'event' to anything you want
5
6
7 tkinter.Label(window, text = "Hi").pack()
‘<Button-1>‘ parameter of bind method is the left clicking event, i.e., when you click
the left button the bind method call the function say_hi
o <Button-1> for left click
o <Button-2> for middle click
o <Button-3> for right click
Here, we are binding the left click event to a button. You can bind it to any
other widget you want.
You will have different parameters for different events
Clicking events are of 3 different types namely leftClick, middleClick,
and rightClick.
Now, you will learn how to call a particular function based on the event that occurs.
Run the following program and click the left, middle, right buttons to calls a
specific function.
That function will create a new label with the mentioned text.
1 import tkinter
2 window = tkinter.Tk()
3 window.title("GUI")
5 def left_click(event):
6
tkinter.Label(window, text = "Left Click!").pack()
7
def middle_click(event):
8
9
10 tkinter.Label(window, text = "Middle Click!").pack()
11 def right_click(event):
12
14 window.bind("Button-1", left_click)
15 window.bind("Button-2", middle_click)
window.bind("Button-3", right_click)
16
window.mainloop()
17
If you run the above program, you will see a blank window. Now, click the left,
middle and right button to call respective functions.
You get the something similar results to the following:
Next up on this Tkinter tutorial blog, we need to check out how we can add images to
our window.
2 window = tkinter.Tk()
window.title("GUI")
3
# taking image from the directory and storing the source in a
4 variable
5 icon = tkinter.PhotoImage(file = "images/edureka.png")
11
12 global expression
13
15
16 input_text.set(expression)
19
20 global expression
21
22 expression = ""
23
input_text.set("")
24
25
# 'btn_equal' calculates the expression present in input field
26
27
def btn_equal():
28
29
global expression
30
31
result = str(eval(expression)) # 'eval' function evalutes the
32 string expression directly
33
# you can also implement your own function to evalute the
34
expression istead of 'eval' function
35
36 input_text.set(result)
37
38 expression = ""
39
40 expression = ""
41
43
44 input_text = StringVar()
45
# creating a frame for the input field
46
47
input_frame = Frame(window, width = 312, height = 50, bd = 0,
48
highlightbackground = "black", highlightcolor = "black",
49 highlightthickness = 1)
50
51 input_frame.pack(side = TOP)
52
54
input_field = Entry(input_frame, font = ('arial', 18, 'bold'),
55
textvariable = input_text, width = 50, bg = "#eee", bd = 0, justify =
56 RIGHT)
57
58 input_field.grid(row = 0, column = 0)
59
input_field.pack(ipady = 10) # 'ipady' is internal padding to
60
increase the height of input field
61
65
66 btns_frame.pack()
67
68 # first row
69
clear = Button(btns_frame, text = "C", fg = "black", width = 32,
70
height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda:
71 btn_clear()).grid(row = 0, column = 0, columnspan = 3, padx = 1, pady
= 1)
72
73
divide = Button(btns_frame, text = "/", fg = "black", width = 10,
74
height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda:
75 btn_click("/")).grid(row = 0, column = 3, padx = 1, pady = 1)
76
77 # second row
78
seven = Button(btns_frame, text = "7", fg = "black", width = 10,
79
height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
80 btn_click(7)).grid(row = 1, column = 0, padx = 1, pady = 1)
81
82
89
multiply = Button(btns_frame, text = "*", fg = "black", width = 10,
90 height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda:
btn_click("*")).grid(row = 1, column = 3, padx = 1, pady = 1)
91
92
# third row
93
94
four = Button(btns_frame, text = "4", fg = "black", width = 10,
95 height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1)
96
97
five = Button(btns_frame, text = "5", fg = "black", width = 10,
98
height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda:
99 btn_click(5)).grid(row = 2, column = 1, padx = 1, pady = 1)
100
107
# fourth row
108
# fourth row
window.mainloop()
Differences Between MongoDB and SQL
Server
There are basically two types of databases present: SQL and NoSQL. The
stores the data in JSON like documents that can vary in structure offerings
solutions. MongoDB is one of the several databases that rise under the
NoSQL database which is used for high volume data storage. Instead of
beforehand. Instead, the fields can be created on the fly. The data model
easily.
Joins Yes No
Transaction ACID NO
Triggers Yes No
Concurrency Yes No
Drivers .NET, Java, PHP, Python, Ruby, Visual Basic Dart, Delph
Java, JavaSc
PHP, Power
Scala, Smal
The pros are that you can move faster with a SQLite database relative
to MySQL and PostgreSQL. That said, you'll be stuck with limited
functionality. You won't be able to customize features or add a ton of
multi-user functionality.
MySQL/PostgreSQL
There are distinct differences between MySQL and PostgreSQL. That
said, given the context of the article, they fit into a similar category.
Both database types are great for enterprise solutions. If you need to
scale fast, MySQL and PostgreSQL are your best bet. They'll provide
long-term infrastructure and bolster your security.
Another reason they're great for enterprises is that they can handle
high performance activities. Longer insert, update, and select
statements need a lot of computing power. You'll be able to write
those statements with less latency than what a SQLite database
would give you.
SQLite, MySQL, and PostgreSQL all have their pros and cons. The
one you select should depend on your project or company's needs.
You should also consider what you need now versus several years
down the road.
Table of Contents
Create Connection
SQLite3 Cursor
Create Database
Create Table
Insert in Table
Update Table
Select statement
Fetch all data
SQLite3 rowcount
List tables
Check if a table exists or not
Drop table
SQLite3 exceptions
o DatabaseError
o IntegrityError
o ProgrammingError
o OperationalError
o NotSupportedError
SQLite3 Executemany (Bulk insert)
Close Connection
SQLite3 datetime
Create Connection
To use SQLite3 in Python, first of all, you will have to import
the sqlite3 module and then create a connection object which will connect us
to the database and will let us execute the SQL statements.
You can a connection object using the connect() function:
import sqlite3
con = sqlite3.connect('mydatabase.db')
That will create a new file with the name ‘mydatabase.db’.
SQLite3 Cursor
To execute SQLite statements in Python, you need a cursor object. You can
create it using the cursor() method.
The SQLite3 cursor is a method of the connection object. To execute the
SQLite3 statements, you should establish a connection at first and then create
an object of the cursor using the connection object as follows:
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
Now we can use the cursor object to call the execute() method to execute any
SQL queries.
Create Database
When you create a connection with SQLite, that will create a database file
automatically if it doesn’t already exist. This database file is created on disk;
we can also create a database in RAM by using :memory: with the connect
function. This database is called in-memory database.
Consider the code below in which we have created a database with
a try, except and finally blocks to handle any exceptions:
import sqlite3
from sqlite3 import Error
def sql_connection():
try:
con = sqlite3.connect(':memory:')
except Error:
print(Error)
finally:
con.close()
sql_connection()
After that, we have closed our connection in the finally block. Closing a
connection is optional, but it is a good programming practice, so you free the
memory from any unused resources.
Create Table
To create a table in SQLite3, you can use the Create Table query in
the execute() method. Consider the following steps:
1. Create a connection object.
2. From the connection object, create a cursor object.
3. Using the cursor object, call the execute method with create table
query as the parameter.
Let’s create employees with the following attributes:
employees (id, name, salary, department, position, hireDate)
def sql_connection():
try:
con = sqlite3.connect('mydatabase.db')
return con
except Error:
print(Error)
def sql_table(con):
cursorObj = con.cursor()
cursorObj.execute("CREATE TABLE employees(id integer PRIMARY KEY, name text, salary real,
department text, position text, hireDate text)")
con.commit()
con = sql_connection()
sql_table(con)
In the above code, we have defined two methods, the first one establishes a
connection and the second method creates a cursor object to execute the
create table statement.
The commit() method saves all the changes we make. In the end, both
methods are called.
To check if our table is created, you can use the DB browser for SQLite to
view your table. Open your mydatabase.db file with the program, and you
should see your table:
Insert in Table
To insert data in a table, we use the INSERT INTO statement. Consider the
following line of code:
cursorObj.execute("INSERT INTO employees VALUES(1, 'John', 700, 'HR', 'Manager', '2017-01-04')")
con.commit()
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
sql_insert(con, entities)
Update Table
To update the table, simply create a connection, then create a cursor object
using the connection and finally use the UPDATE statement in
the execute() method.
Suppose that we want to update the name of the employee whose id equals 2.
For updating, we will use the UPDATE statement and for the employee
whose id equals 2. We will use the WHERE clause as a condition to select
this employee.
Consider the following code:
import sqlite3
con = sqlite3.connect('mydatabase.db')
def sql_update(con):
cursorObj = con.cursor()
con.commit()
sql_update(con)
Select statement
You can use the select statement to select data from a particular table. If you
want to select all the columns of the data from a table, you can use the
asterisk (*). The syntax for this will be as follows:
select * from table_name
For example,
cursorObj.execute('SELECT id, name FROM employees')
The select statement selects the required data from the database table, and if
you want to fetch the selected data, the fetchall() method of the cursor object
is used. We will demonstrate this in the next section.
con = sqlite3.connect('mydatabase.db')
def sql_fetch(con):
cursorObj = con.cursor()
rows = cursorObj.fetchall()
sql_fetch(con)
The above code will print out the records in our database as follows:
If you want to fetch specific data from the database, you can use the WHERE
clause. For example, we want to fetch the ids and names of those employees
whose salary is greater than 800. For this, let’s populate our table with more
rows, then execute our query.
You can use the insert statement to populate the data, or you can enter them
manually in the DB browser program.
Now, to fetch id and names of those who have a salary greater than 800:
import sqlite3
con = sqlite3.connect('mydatabase.db')
def sql_fetch(con):
cursorObj = con.cursor()
rows = cursorObj.fetchall()
for row in rows:
print(row)
sql_fetch(con)
SQLite3 rowcount
The SQLite3 rowcount is used to return the number of rows that are affected
or selected by the latest executed SQL query.
When we use rowcount with the SELECT statement, -1 will be returned as
how many rows are selected is unknown until they are all fetched. Consider
the example below:
print(cursorObj.execute('SELECT * FROM employees').rowcount)
Therefore, to get the row count, you need to fetch all the data, and then get
the length of the result:
rows = cursorObj.fetchall()
When you use the DELETE statement without any condition (a where
clause), that will delete all the rows in the table, and it will return the total
number of deleted rows in rowcount.
print(cursorObj.execute('DELETE FROM employees').rowcount)
con = sqlite3.connect('mydatabase.db')
def sql_fetch(con):
cursorObj = con.cursor()
print(cursorObj.fetchall())
sql_fetch(con)
For example:
import sqlite3
con = sqlite3.connect('mydatabase.db')
def sql_fetch(con):
cursorObj = con.cursor()
cursorObj.execute('create table if not exists projects(id integer, name text)')
con.commit()
sql_fetch(con)
Similarly, to check if the table exists when deleting, we use “if exists” with
the DROP TABLE statement as follows:
drop table if exists table_name
For example,
cursorObj.execute('drop table if exists projects')
We can also check if the table we want to access exists or not by executing
the following query:
cursorObj.execute('SELECT name from sqlite_master WHERE type = "table" AND name = "employees"')
print(cursorObj.fetchall())
For example,
import sqlite3
con = sqlite3.connect('mydatabase.db')
def sql_fetch(con):
cursorObj = con.cursor()
con.commit()
sql_fetch(con)
SQLite3 exceptions
Exceptions are the run time errors. In Python programming, all exceptions
are the instances of the class derived from the BaseException.
In SQLite3, we have the following main Python exceptions:
DatabaseError
Any error related to the database raises the DatabaseError.
IntegrityError
IntegrityError is a subclass of DatabaseError and is raised when there is a
data integrity issue. For example, foreign data isn’t updated in all tables
resulting in the inconsistency of the data.
ProgrammingError
The exception ProgrammingError raises when there are syntax errors or table
is not found or function is called with the wrong number of parameters/
arguments.
OperationalError
This exception is raised when the database operations are failed, for example,
unusual disconnection. This is not the fault of the programmers.
NotSupportedError
When you use some methods that aren’t defined or supported by the
database, that will raise the NotSupportedError exception.
SQLite3 Executemany (Bulk insert)
You can use the executemany statement to insert multiple rows at once.
Consider the following code:
import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
data = [(1, "Ridesharing"), (2, "Water Purifying"), (3, "Forensics"), (4, "Botany")]
con.commit()
Here we created a table with two columns, and “data” has four values for
each column. We pass the variable to the executemany() method along with
the query.
Note that we have used the placeholder to pass the values.
The above code will generate the following result:
Close Connection
Once you are done with your database, it is a good practice to close the
connection. You can close the connection by using the close() method.
To close a connection, use the connection object and call the close() method
as follows:
con = sqlite3.connect('mydatabase.db')
#program statements
con.close()
SQLite3 datetime
In the Python SQLite3 database, we can easily store date or time by
importing the datatime module. The following formats are the most common
formats you can use for datetime:
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
import datetime
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute('create table if not exists assignments(id integer, name text, date date)')
data = [(1, "Ridesharing", datetime.date(2017, 1, 2)), (2, "Water Purifying", datetime.date(2018, 3, 4))]
con.commit()
In this code, we imported the datetime module first, and we have created a
table named assignments with three columns.
The data type of the third column is a date. To insert the date in the column,
we have used datetime.date. Similarly, we can use datetime.time to handle
time.
The above code will generate the following output:
The great flexibility and mobility of the SQLite3 database make it the first
choice for any developer to use it and ship it with any product he works with.
You can use SQLite3 databases in Windows, Linux, Mac OS, Android, and
iOS projects due to their awesome portability. So you ship one file with your
project and that’s it.