Unit 5 GUI Programming Tkinter
Unit 5 GUI Programming Tkinter
Table of Contents
8.1 GUI Programming ....................................................................................................... 2
8.2 Introduction to Tkinter................................................................................................ 2
8.2.1 Importing Tkinter Module ........................................................................................................ 3
8.2.2 Creating window ....................................................................................................................... 3
8.3 Basic Attributes of tkinter Window ............................................................................. 3
8.3.1 Set Title and Background of Window ....................................................................................... 3
8.3.2 Resize the window .................................................................................................................... 4
8.3.3 Resizing behavior ...................................................................................................................... 5
8.3.4 Changing the default icon at Title Bar ...................................................................................... 5
8.4 Widgets ...................................................................................................................... 6
8.4.1 Label Widgets ............................................................................................................................ 6
8.4.2 Entry Widgets ............................................................................................................................ 8
8.4.3 Buttons Widgets ...................................................................................................................... 10
8.4.4 Checkbutton Widgets .............................................................................................................. 10
8.4.5 Radiobutton Widgets .............................................................................................................. 11
8.4.6 Frame Widgets ........................................................................................................................ 12
8.4.7 MessageBox Widgets .............................................................................................................. 13
8.5 Layout Management / Geometry Management ......................................................... 15
8.5.1 Pack () - It packs the widget in rows or columns. ................................................................... 15
8.5.2 grid() ........................................................................................................................................ 16
8.5.3 place......................................................................................................................................... 17
8.6 Tkinter Variables....................................................................................................... 18
8.7 Tkinter command binding ......................................................................................... 19
8.8 Passing Arguments to command in tkinter Button ..................................................... 20
8.9 Demo of Basic Calculator App ................................................................................... 21
8.9.1. GUI Code ................................................................................................................................. 21
8.9.2 Complete Basic code with Call-back Function to act on pressing Button on calculator ....... 22
8.10 Tkinter and Database(MySQL) ................................................................................. 23
Reference ....................................................................................................................... 26
8.1 GUI Programming
A GUI or a graphical user interface is an interactive environment to take responses from users
on various situations such as forms, documents, tests, etc. Python provides multiple options
for developing graphical user interfaces (GUIs).
Most important are listed below.
• Tkinter
• PyQT5
• PySide 2
• Kivy
• wxPython etc.
In this chapter, we will discuss Tkinter. Figure 8.1 shows the three components of GUI
programming:
Tkinter is one of the most popular Python GUI libraries for developing desktop applications.
Tkinter provides diverse widgets such as labels, buttons, text boxes, checkboxes, etc., that
are used in a graphical user interface application.
• A main window or container - this is what will be drawn on the screen for the user to
use.
• A widget such as a label, entry, button, frame, etc.
• A Geometry manager – To place a widget in the window, Tkinter has particular
function called geometry managers. Like pack, gride, and place. We will discuss each
in detail.
8.2.1 Importing Tkinter Module
Tkinter module is part of the standard library. To use tkinter, import the tkinter module
using the below-given code(Figure-8.2.1).
Tkinter's Tk class instance creates a window. In the below code, we created an object of Tk()
and named it window. Tk() method creates a blank window with close, maximize and
minimize buttons as shown in figure 8.2.2, and the mainloop() method is used to display the
window until you manually close it.
Output -
We used the title() method for setting the title and used the configure() method for
background color.
Syntax – To set Title window.title(string)
To set Background window.configure(background=color)
Note - We can use either standard color ( black, red, white, etc.) or hexadecimal digits
representing RGB.
Example – Create a Blank Window and set background color red, title as "My first GUI
Application” as shown in figure 8.3.1.
geometry() method is used to resize the window. We have to provide the dimension (width
X height (in px)) of the window as a string, as shown in Figure 8.3.2.
By default, we can resize a window when it displays through mouse selection. To prevent
the window from resizing, we can use the resizable () method. resizable() method takes two
parameters (width, height). If you want to disable width and height, then pass True/False,
respectively.
Output -
To change the default icon at the top of the window, we used iconbitmap() method of the
window object. It only takes. ioc file. The example is shown in Figure 8.3.4
Output-
8.4 Widgets
Tkinter provides various controls, such as labels, text boxes, radio buttons, submit buttons,
etc., used in a GUI application. These controls are commonly called widgets.
A Label is used to display text or an image. The label is a widget that the user just views but
does not interact with.
master – This represents the window object; means in which window you want to add.
option – Entry widgets have the following option
• text - To display one or more lines of text in a label widget
• fg – To set Text Color
• bg – To set the background color of the text
• font – To set font style, size, bold, italic.
• image – Image as a label
• Reference for more options - https://tkdocs.com/shipman/label.html
Example – Create two labels with the text "This is my first Label" and "This is Second Label"
and place them in the window object. The code is given in figure 8.4.1(a). label () is used to
create a Label. For example pack() method is used to place the widget in the window. Details
about pack() will be discussed in section 8.5 (Layout Management ). At this point, only
remember that every widget must be added to the window object using the layout
management method ( pack(), grid(), place).
Output-
Example –2 To display label having text in "yellow", background in "dark green", font style
in "Helvetica", size 16.
Output-
To add an image to the label, we have to create a name for the image using the PhotoImage()
method. PhotoImage() - Create an image with NAME and display pictures in PGM, PPM, GIF,
PNG format. If you want to use another format's image, then use the pillow package.
An example of the image inside the label is shown in figure 8.4.2( c).
Output -
Example – 1 Create a window having one label and a Textbox (Entry widget)
Output -
Figure 8.4.2(a) show the code and output of a window having one label and a Textbox.
Example –2 Create a window with one label and a Textbox where enter text color will be
red.
Output -
Figure 8.4.2(b) show the code and output of a window having one label and a Textbox
where when user enter any text then text will be displayed in red color.
8.4.3 Buttons Widgets
Example – Create a window having two buttons as shown in Figure 8.4.3 Output
Output -
The Checkbutton widget is used to display several options to a user as toggle buttons.
Example – Create a window and place three checkbutton as shown in figure 8.4.4
Output -
This widget implements a multiple-choice button. Only one radio button in a group can be
selected at a time.
Example – Create a window having two radio button, one label with male and second with
Female as shown in figure 8.4.5
Output -
A frame is just a container for other widgets. It is used for grouping and organizing other
widgets in a somehow friendly way.
Example - Create Two frames and pack them left side and right side. Add two buttons on
each frame as shown in figure 8.4.6.
Output -
FunctionName − Name of the appropriate message box function. Figure 8.4.7(a) shows
different types of function used for the message box.
Figure 8.4.7(a) Different type of message box and its function name
Example - Create a Button and call a function name show_msg() which displays a message
using messageBox.
The purpose of Geometry Management is to organize widgets in the parent area. Tkinter
possesses three layout managers:
• pack()
• grid()
• place()
Note - Never mixed all three layout managers in the same window.
Example 1 – Create four buttons and pack them left, right, top, and bottom side.
Output -
As shown in Figure 8.5.1(a), to pack button widgets we used pack() method and set value of
side with “LEFT”, “RIGHT”, “TOP”, “BOTTOM”.
Example 2 – Create Two buttons, pack the first button using fill=X and second as default.
Output -
Figure 8.5.1(b) Example of the pack() layout manager and fill=X option
Fill=X, in pack() method set button widgets as wide as the parent widget as shown in Figure
8.5.1(b).
8.5.2 grid()
This geometry manager organizes widgets in a table-like structure (Figure 8.5.2(a)) in the
parent widget.
grid_options -
• column - The column number where you want the widget gridded, counting from
zero. The default value is zero.
• columnspan - Defines the number of columns a cell should span.
• row - The row number into which you want to insert the widget, counting from 0.
• rowspan - rowspan specifies the number of rows a cell should span.
• For more option - https://tkdocs.com/shipman/grid.html
Output -
To create a grid of 3X3, we set row and column option in grid method as shown in Figure
8.5.2(b).
8.5.3 place
This geometry manager organizes widgets by placing them in a specific position in the
parent widget.
Syntax - widget.place( place_options )
place_options -
• height, width − Height and width in pixels.
• anchor − The exact spot of widget other options refers to: maybe N, E, S, W, NE, NW,
SE, or SW.
• x, y − Horizontal and vertical coordinate in pixels. In the window at topmost corner
coordinate is (0,0).
Example – Given the below code, place two buttons at a different coordinate.
Output -
To place widgets at different coordinates we set value of x (for x coordinate) and y (for y
coordinate) in place() method as shown in Figure 8.5.3.
Methods – it has two methods to set or get value to/from the widget.
Widgets are essential to make an application interactive. Widgets respond to the events by:
• Mouse clicks
• Key presses
Widgets require assigning a callback function to a specific event. When the event occurs, the
callback will be invoked automatically to handle the event. In Tkinter, some widgets allow you
to associate a callback function with an event using the command binding.
To use command binding, we first define a function as a callback and then assign the
function's name to the command option of the widgets.
Example – Create a login page and display a message through messages box if user_name=
admin and password = admin; otherwise, display Wrong username and password as shown
in Figure 8.7(b).
In the figure8.7(a), we created a function check () which display message using message box
on given condition. To call check () function when button will press, we use < command =
name_of_function > option.
We can pass the parameter to the callback function using the lambda operator when the
Button is clicked. The figure8.8 below shows the code.
Output -
The development of the Basic Calculator app will be divided into two parts.
1. GUI
2. Callback Function to act on pressing Button.
8.9.1. GUI Code - The code of Simple Calculator is shown in Figure 8.9(a). In this we create 15
Buttons for digits (0-9), operator (+, -, *, /, =) and one entry box for displaying calculation.
Output -
Output -
Python needs a MySQL driver to access the MySQL database. So first, we install the mysql-
connector-python package using the below command
There are the following steps to connect a python application to our database.
• Import mysql.connector module
• Create the connection object
• Create the cursor object
• Execute the SQL query
Import mysql.connector module - To import the module, we used the below code.
Create the connection object – To create a connection with MySQL database, we used
connect() method of mysql.connector module.
Create the cursor object - The cursor object is used to execute SQL queries to the
database.
Execute the query - To execute SQL queries, execute() method of the cursor object is used.
fetchall() – We use the fetchall() method, fetched all rows from the last executed
statement.
Syntax – myresult = my_cursor.fetchall()
Example – Create a login form and connect to a database to check username and
password with MySql Database.
In example Figure 8.10(a), we create a database "test," and in the "test" database, we created
a table "users". In table users, there are two fields (username, password). Figure 8.10(b)
shows the phpMyAdmin page.
Figure 8.10(b) phpMyAdmin page
Reference
1. https://tkdocs.com/
2. https://docs.python.org/3/library/tkinter.html
3. https://www.python-course.eu/python_tkinter.php
4. Tkinter 8.5 reference: aGUI for Python, John W. Shipman
5. Python GUI Programming with Tkinter: Develop responsive and powerful GUI applications
with Tkinter by Alan D. Moore, Packt.
6. Python and Tkinter Programming, by John E Grayson, Manning Publications Co.