0% found this document useful (0 votes)
126 views

Unit 5 GUI Programming Tkinter

This document discusses Tkinter, a GUI programming library for Python. It introduces Tkinter components like main windows, widgets, and geometry managers. It then covers the basic attributes of Tkinter windows like setting title, background, resizing behavior and icon. Various widgets like labels, entry boxes, buttons, checkboxes and radiobuttons are explained along with examples. Finally, it discusses layout management techniques like pack, grid and place and Tkinter variables, command binding and building a basic calculator app.

Uploaded by

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

Unit 5 GUI Programming Tkinter

This document discusses Tkinter, a GUI programming library for Python. It introduces Tkinter components like main windows, widgets, and geometry managers. It then covers the basic attributes of Tkinter windows like setting title, background, resizing behavior and icon. Various widgets like labels, entry boxes, buttons, checkboxes and radiobuttons are explained along with examples. Finally, it discusses layout management techniques like pack, grid and place and Tkinter variables, command binding and building a basic calculator app.

Uploaded by

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

Chapter 8

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:

Figure 8.1 Components of GUI

8.2 Introduction to Tkinter

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.

Tkinter gives us the following component to create a GUI 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).

Figure-8.2.1 import tkinter module

8.2.2 Creating window

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 -

Figure 8.2.2 Creating Blank Window

8.3 Basic Attributes of tkinter Window

8.3.1 Set Title and Background of Window

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.

Figure 8.3.1 Set Title and Background of window

8.3.2 Resize the window

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.

Figure 8.3.2 Resize the window


8.3.3 Resizing behavior

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.

Example – Change the resizing behavior of the tkinter window .

Output -

Figure 8.3.3 Resizable window

8.3.4 Changing the default icon at Title Bar

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-

Figure 8.3.4 Changing the default icon at Title Bar

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.

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

Syntax - l = Label (master, option, ...)

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-

Figure 8.4.1(a) Label Widgets

Example –2 To display label having text in "yellow", background in "dark green", font style
in "Helvetica", size 16.

Output-

Figure 8.4.1(b) Example 2

Using Images in Labels -

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 -

Figure 8.4.1(c) Image in the label

8.4.2 Entry Widgets


Entry widgets are the basic widgets of Tkinter used to get input, i.e., text strings, from an
application user. This widget allows the user to enter a single line of text.

Syntax - e = Entry (master, option, ... )

master – This represents the window


option – Entry widgets have the following option
• bg - To set the Background color of textbox
• font - To set font style used for the text.
• fg - The color used to render the text.
• show - Normally, the characters that the user types appear in the entry. To make a
password entry that echoes each character like an asterisk, set show = "*".
• textvariable - To be able to retrieve the current text from your entry widget.
• Reference for more options - https://tkdocs.com/shipman/entry.html

Example – 1 Create a window having one label and a Textbox (Entry widget)
Output -

Figure 8.4.2 (a)Entry Widgets

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) Example of Entry widget with text color red

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

The Button widget is used to add buttons in a Python application.

Syntax - b = Button (master, option = value, ... )

master – This represents the window


option – Buttons widgets have the following option
• text – To set the text of Button
• bg - To set the Background color
• fg – To set Text-color of Button
• height - Height of the button in text lines
• image - Image to be displayed on the button
• justify - To show multiple text lines: LEFT to left-justify each line; CENTER to center
them; or RIGHT to right-justify.
• Reference for more options - https://tkdocs.com/shipman/button.html

Example – Create a window having two buttons as shown in Figure 8.4.3 Output

Output -

Figure 8.4.3 Example of Buttons Widgets

8.4.4 Checkbutton Widgets

The Checkbutton widget is used to display several options to a user as toggle buttons.

Syntax – c = Checkbutton(master, option, ...)

master – This represents the window


option – Checkbutton widgets have the following option
• bg - To set Background color
• fg – To set the Text color of Button
• selectcolor – To set checkbutton color.
• text - The label is displayed next to the checkbutton.
• offvalue - Normally, a checkbutton's associated control variable will be set to 0 when
it is cleared (off). You can supply an alternate value for the off-state by setting off value
to that value.
• onvalue - Normally, a checkbutton's associated control variable will be set to 1 when
set (on). You can supply an alternate value for on the state by setting on value to that
value.
• Reference for more options - https://tkdocs.com/shipman/checkbutton.html

Example – Create a window and place three checkbutton as shown in figure 8.4.4

Output -

Figure 8.4.4 Example of Checkbutton Widgets

8.4.5 Radiobutton Widgets

This widget implements a multiple-choice button. Only one radio button in a group can be
selected at a time.

Syntax - r = Radiobutton (master, option, ... )

master – This represents the window


option – radiobutton widgets have the following option
• bg - To set the Background color
• fg – To set Text-color of Button
• text - The label is displayed next to the rediobutton.
• value - When the user turns on a radiobutton, its control variable is set to its current
value option.
• Reference for more options - https://tkdocs.com/shipman/radiobutton.html

Example – Create a window having two radio button, one label with male and second with
Female as shown in figure 8.4.5

Output -

Figure 8.4.5 Example of Radiobutton Widgets

8.4.6 Frame Widgets

A frame is just a container for other widgets. It is used for grouping and organizing other
widgets in a somehow friendly way.

Syntax - f = Frame ( master, option, ... )

master – This represents the window


option – frame widgets have the following option
• bd or border-width – It is used for border width
• bg or background – Set background-color
• height – To set the height of the frame
• width – Set width if the frame
• Reference for more options - https://tkdocs.com/shipman/frame.html

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 -

Figure 8.4.6 Example of Frame Widgets

8.4.7 MessageBox Widgets

MessageBox() module is used to display message boxes in your applications.

Syntax - messagebox.FunctionName(title, message [, options])

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

title − Text to be displayed in the title bar of a message box.


message − This is the text to be displayed as a message.

Example - Create a Button and call a function name show_msg() which displays a message
using messageBox.

Figure 8.4.7(b) Example of MessageBox


We call function show_msg() using command option in Button widgets as shown in Figure
8.4.7(b).
8.5 Layout Management / Geometry Management

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.

8.5.1 Pack () - It packs the widget in rows or columns.

Syntax - widget.pack( pack_options )

Following are pack_option -


• side − Determines which side of the parent widget packs against TOP (default),
BOTTOM, LEFT, or RIGHT.
• fill – It is used to make the widgets as wide as the parent widget; you have to use the
fill=X

Example 1 – Create four buttons and pack them left, right, top, and bottom side.

Output -

Figure 8.5.1(a) Example of pack() layout manager with a side option

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.

Figure 8.5.2(a) table-like structure


Syntax - widget.grid( grid_options )

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

Example – Create a grid of 3X3 having nine buttons.

Output -

Figure 8.5.2(b) Example of grid layout manager

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 -

Figure 8.5.3 Example of place layout manager

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.

8.6 Tkinter Variables

To manipulate the values of widgets, Tkinter have following variables class


• Variable1 = StringVar() - It holds a string. Default value “”
• Variable2 = IntVar() - It holds an integer. Default value 0
• Variable3 = DoubleVar() - It holds float. Default value 0.0
• Variable4 = BooleanVar() - It holds boolean i.e. 0/1.

Methods – it has two methods to set or get value to/from the widget.

set () - Used to set variable value


get() - Used to get value from variable
8.7 Tkinter command binding

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.

To understand command binding, let's take an example.

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.

Figure 8.7(a) Example to call a function when button press


Figure 8.7(b) Output of figure 8.7(a) code

8.8 Passing Arguments to command in tkinter Button

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 -

Figure 8.8: Passing Arguments to command in tkinter Button


8.9 Demo of Basic Calculator App

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 -

Figure 8.9(a) GUI of Basic Calculator app


8.9.2 Complete Basic code with Call-back Function to act on pressing Button on calculator -
This calculator will evaluate any expression written as a sequence of operand and operator.
In this we create two function digit() and equal(). digit() function is used to concatenate all
pressed button's text into a string name "var." The complete code is shown in figure 8.9(b).

Output -

Figure 8.9(b) Complete Code of Basic Calculator


8.10 Tkinter and Database(MySQL)

8.10.1 Installation of mysql-connector-python package

Python needs a MySQL driver to access the MySQL database. So first, we install the mysql-
connector-python package using the below command

pip install mysql-connector-python

8.10.2 Database Connection

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.

import mysql.connector as mysql

Create the connection object – To create a connection with MySQL database, we used
connect() method of mysql.connector module.

Syntax - db = mysql.connect(host =" ",user = "", password="",db ="")

host – address of MySQL server


user - user name to access the database if given; otherwise, leave it blank
Password – Password to access the database if provided otherwise, leave it blank
db – Database name

Create the cursor object - The cursor object is used to execute SQL queries to the
database.

Syntax - my_cursor = db.cursor()

Execute the query - To execute SQL queries, execute() method of the cursor object is used.

Syntax - my_cursor.execute(“your sql query as string”)

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.

Figure 8.10(a) Login Page with Database Connectivity

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.

You might also like