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

Chap-4] GUI Programming and Database Connectivity Using Python

The document provides an overview of GUI programming and database connectivity using Python, focusing on the Tkinter module for creating graphical user interfaces. It details various GUI elements, their benefits, and examples of GUI operating systems and interfaces. Additionally, it outlines the use of Tkinter widgets, including buttons, labels, and message boxes, along with their configurations and functionalities.

Uploaded by

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

Chap-4] GUI Programming and Database Connectivity Using Python

The document provides an overview of GUI programming and database connectivity using Python, focusing on the Tkinter module for creating graphical user interfaces. It details various GUI elements, their benefits, and examples of GUI operating systems and interfaces. Additionally, it outlines the use of Tkinter widgets, including buttons, labels, and message boxes, along with their configurations and functionalities.

Uploaded by

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

MMN Python

Chap – 4] GUI Programming and Database Connectivity Using


Python
4.1] Graphical User Interfaces
 A GUI (graphical user interface) is a system of interactive visual
components for computer software.
 A GUI displays objects that convey information, and represent actions
that can be taken by the user.
 The objects change color, size, or visibility when the user interacts
with them.
 The GUI was first developed at Xerox PARC by Alan Kay, Douglas
Engelbart, and a group of other researchers in 1981.
 Later, Apple introduced the Lisa computer with a GUI on January
19, 1983.
 GUI is often pronounced by saying each letter (G-U-I or gee-you-eye).
 It sometimes is also pronounced as "gooey."
 A GUI includes GUI objects, like icons, cursors, and buttons.
 These graphical elements are sometimes enhanced with sounds, or
visual effects like transparency and drop shadows. Using these
objects, a user can use the computer without having to know
commands.

Below is a picture of the Windows 7 desktop and an example of a


GUI operating system. In this example, you could use a mouse to
move a pointer and click a program icon to start a program.

Mr. D. S. Kiwde Page 1


MMN Python

Elements of a GUI?

To make a GUI as user-friendly as possible, there are different


elements and objects that the user uses to interact with the software.

Below is a list of each of these with a brief description.

 Button - A graphical representation of a button that performs an


action in a program when pressed
 Dialog box - A type of window that displays additional information,
and asks a user for input.
 Icon - Small graphical representation of a program, features, or file.
 Menu - List of commands or choices offered to the user through the
menu bar.
 Menu bar - Thin, horizontal bar containing the labels of menus.
 Ribbon - Replacement for the file menu and toolbar that groups
programs activities together.
 Tab - Clickable area at the top of a window that shows another page
or area.
 Toolbar - Row of buttons, often near the top of an application window
that controls software functions.
 Window - Rectangular section of the computer's display that shows
the program currently being used.

Benefits of GUI?

 A GUI is considered to be more user-friendly than a text-


based command-line interface, such as MS-DOS, or the shell of Unix-
like operating systems.
 Unlike a command-line operating system or CUI, like Unix or MS-DOS,
GUI operating systems are easier to learn and use because commands
do not need to be memorized.
 Additionally, users do not need to know any programming languages.
Because of their ease of use and more modern appearance, GUI
operating systems have come to dominate today's market.

Examples of a GUI operating system

 Microsoft Windows
 Apple System 7 and macOS
 Chrome OS

Mr. D. S. Kiwde Page 2


MMN Python

 Linux variants like Ubuntu using a GUI interface.

Examples of a GUI interface

1. Apple macOS

2. Microsoft Windows

3. GNOME

4. KDE

5. Any Microsoft program, including Word, Excel, and Outlook.

6. Internet browsers, such as Internet Explorer, Chrome,


and Firefox.

4.2] Using the tkinter Module


 Python provides the standard library Tkinter for creating the graphical
user interface for desktop based applications.

An empty Tkinter top-level window can be created by using the following


steps.

1. import the Tkinter module.


2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the
user's computer screen.

Example

Mr. D. S. Kiwde Page 3


MMN Python

Tkinter widgets

There are various widgets like button, canvas, checkbutton, entry, etc.
that are used to build the python GUI applications.

SN Widget Description

1 Button The Button is used to add various kinds of buttons to the


python application.

2 Canvas The canvas widget is used to draw the canvas on the


window.

3 Checkbutton The Checkbutton is used to display the CheckButton on the


window.

4 Entry The entry widget is used to display the single-line text field
to the user. It is commonly used to accept user values.

5 Frame It can be defined as a container to which, another widget


can be added and organized.

6 Label A label is a text used to display some message or


information about the other widgets.

7 ListBox The ListBox widget is used to display a list of options to


the user.

8 Menubutton The Menubutton is used to display the menu items to the


user.

9 Menu It is used to add menu items to the user.

10 Message The Message widget is used to display the message-box to


the user.

11 Radiobutton The Radiobutton is different from a checkbutton. Here, the


user is provided with various options and the user can
select only one option among them.

12 Scale It is used to provide the slider to the user.

13 Scrollbar It provides the scrollbar to the user so that the user can
scroll the window up and down.

Mr. D. S. Kiwde Page 4


MMN Python

14 Text It is different from Entry because it provides a multi-line


text field to the user so that the user can write the text
and edit the text inside it.

14 Toplevel It is used to create a separate window container.

15 Spinbox It is an entry widget used to select from options of values.

16 PanedWindow It is like a container widget that contains horizontal or


vertical panes.

17 LabelFrame A LabelFrame is a container widget that acts as the


container

18 MessageBox This module is used to display the message-box in the


desktop based applications.

4.3] Creating Label, Text, Button, info Dialog Boxes, Radiobutton,


Checkbutton
Label

 The Label is used to specify the container box where we can place the
text or images.
 This widget is used to provide the message to the user about other
widgets used in the python application.

There are the various options which can be specified to configure the text
or the part of the text shown in the Label.

The syntax to use the Label is given below.

Syntax
w = Label (master, options)

A list of possible options is given below.

SN Option Description

1 anchor It specifies the exact position of the text within the size
provided to the widget. The default value is CENTER, which
is used to center the text within the specified space.

2 bg The background color displayed behind the widget.

Mr. D. S. Kiwde Page 5


MMN Python

3 bitmap It is used to set the bitmap to the graphical object specified


so that, the label can represent the graphics instead of text.

4 bd It represents the width of the border. The default is 2 pixels.

5 cursor The mouse pointer will be changed to the type of the cursor
specified, i.e., arrow, dot, etc.

6 font The font type of the text written inside the widget.

7 fg The foreground color of the text written inside the widget.

8 height The height of the widget.

9 image The image that is to be shown as the label.

10 justify It is used to represent the orientation of the text if the text


contains multiple lines. It can be set to LEFT for left
justification, RIGHT for right justification, and CENTER for
center justification.

11 padx The horizontal padding of the text. The default value is 1.

12 pady The vertical padding of the text. The default value is 1.

13 relief The type of the border. The default value is FLAT.

14 text This is set to the string variable which may contain one or
more line of text.

15 textvariable The text written inside the widget is set to the control
variable StringVar so that it can be accessed and changed
accordingly.

16 underline We can display a line under the specified letter of the text.
Set this option to the number of the letter under which the
line will be displayed.

17 width The width of the widget. It is specified as the number of


characters.

18 wraplength Instead of having only one line as the label text, we can
break it to the number of lines where each line has the
number of characters specified to this option.

Mr. D. S. Kiwde Page 6


MMN Python

Output:

Text

 The Text widget is used to show the text data on the Python
application.
 However, Tkinter provides us the Entry widget which is used to
implement the single line text box.
 The Text widget is used to display the multi-line formatted text with
various styles and attributes.
 The Text widget is mostly used to provide the text editor to the user.
 We can also use the windows and images with the Text as it can also
be used to display the formatted text.

The syntax to use the Text widget is given below.

Syntax
w = Text (top, options)

Mr. D. S. Kiwde Page 7


MMN Python

A list of possible options that can be used with the Text widget is given
below.

SN Option Description

1 bg The background color of the widget.

2 bd It represents the border width of the widget.

3 cursor The mouse pointer is changed to the specified cursor


type, i.e. arrow, dot, etc.

4 exportselection The selected text is exported to the selection in the


window manager. We can set this to 0 if we don't
want the text to be exported.

5 font The font type of the text.

6 fg The text color of the widget.

7 height The vertical dimension of the widget in lines.

8 highlightbackground The highlightcolor when the widget doesn't has the


focus.

9 highlightthickness The thickness of the focus highlight. The default


value is 1.

10 highlighcolor The color of the focus highlight when the widget has
the focus.

11 insertbackground It represents the color of the insertion cursor.

12 insertborderwidth It represents the width of the border around the


cursor. The default is 0.

13 insertofftime The time amount in Milliseconds during which the


insertion cursor is off in the blink cycle.

14 insertontime The time amount in Milliseconds during which the


insertion cursor is on in the blink cycle.

15 insertwidth It represents the width of the insertion cursor.

16 padx The horizontal padding of the widget.

Mr. D. S. Kiwde Page 8


MMN Python

17 pady The vertical padding of the widget.

18 relief The type of the border. The default is SUNKEN.

19 selectbackground The background color of the selected text.

20 selectborderwidth The width of the border around the selected text.

21 spacing1 It specifies the amount of vertical space given above


each line of the text. The default is 0.

22 spacing2 This option specifies how much extra vertical space


to add between displayed lines of text when a logical
line wraps. The default is 0.

23 spacing3 It specifies the amount of vertical space to insert


below each line of the text.

24 state It the state is set to DISABLED, the widget becomes


unresponsive to the mouse and keyboard
unresponsive.

25 tabs This option controls how the tab character is used to


position the text.

26 width It represents the width of the widget in characters.

27 wrap This option is used to wrap the wider lines into


multiple lines. Set this option to the WORD to wrap
the lines after the word that fit into the available
space. The default value is CHAR which breaks the
line which gets too wider at any character.

28 xscrollcommand To make the Text widget horizontally scrollable, we


can set this option to the set() method of Scrollbar
widget.

29 yscrollcommand To make the Text widget vertically scrollable, we


can set this option to the set() method of Scrollbar
widget.

Mr. D. S. Kiwde Page 9


MMN Python

Output

Button

 The button widget is used to add various types of buttons to the


python application.
 Python allows us to configure the look of the button according to our
requirements.

We can also associate a method or function with a button which is called


when the button is pressed.

The syntax to use the button widget is given below.

Mr. D. S. Kiwde Page 10


MMN Python

Syntax
W = Button (parent, options)

A list of possible options is given below.

SN Option Description

1 activebackground It represents the background of the button when the


mouse hover the button.

2 activeforeground It represents the font color of the button when the


mouse hover the button.

3 Bd It represents the border width in pixels.

4 Bg It represents the background color of the button.

5 Command It is set to the function call which is scheduled when


the function is called.

6 Fg Foreground color of the button.

7 Font The font of the button text.

8 Height The height of the button. The height is represented in


the number of text lines for the textual lines or the
number of pixels for the images.

10 Highlightcolor The color of the highlight when the button has the
focus.

11 Image It is set to the image displayed on the button.

12 justify It illustrates the way by which the multiple text lines


are represented. It is set to LEFT for left justification,
RIGHT for the right justification, and CENTER for the
center.

13 Padx Additional padding to the button in the horizontal


direction.

14 pady Additional padding to the button in the vertical


direction.

Mr. D. S. Kiwde Page 11


MMN Python

15 Relief It represents the type of the border. It can be


SUNKEN, RAISED, GROOVE, and RIDGE.

17 State This option is set to DISABLED to make the button


unresponsive. The ACTIVE represents the active state
of the button.

18 Underline Set this option to make the button text underlined.

19 Width The width of the button. It exists as a number of


letters for textual buttons or pixels for image buttons.

20 Wraplength If the value is set to a positive number, the text lines


will be wrapped to fit within this length.

Mr. D. S. Kiwde Page 12


MMN Python

Message box

 The messagebox module is used to display the message boxes in the


python applications.
 There are the various functions which are used to display the relevant
messages depending upon the application requirements.

The syntax to use the messagebox is given below.

Syntax
messagebox.function_name(title, message [, options])

Parameters
o function_name: It represents an appropriate message box function.
o title: It is a string which is shown as a title of a message box.
o message: It is the string to be displayed as a message on the
message box.
o options: There are various options which can be used to configure the
message dialog box.

1. showinfo()

 The showinfo() messagebox is used where we need to show some


relevant information to the user.

Example

Mr. D. S. Kiwde Page 13


MMN Python

Output

2. showwarning()

This method is used to display the warning to the user. Consider the
following example.

Example

Output

Mr. D. S. Kiwde Page 14


MMN Python

3. showerror()

This method is used to display the error message to the user. Consider
the following example.

Example

Output

4. askquestion()

This method is used to ask some question to the user which can be
answered in yes or no. Consider the following example.

Mr. D. S. Kiwde Page 15


MMN Python

Example

Output

5. askokcancel()

This method is used to confirm the user's action regarding some


application activity. Consider the following example.

Mr. D. S. Kiwde Page 16


MMN Python

Output

6. askyesno()

This method is used to ask the user about some action to which, the
user can answer in yes or no. Consider the following example.

Example

Output

Mr. D. S. Kiwde Page 17


MMN Python

7. askretrycancel()

This method is used to ask the user about doing a particular task again
or not. Consider the following example.

Example

Output

Radiobutton

 The Radiobutton widget is used to implement one-of-many selection in


the python application.
 It shows multiple choices to the user out of which, the user can select
only one out of them.
 We can display the multiple line text or images on the radiobuttons.

The syntax to use the Radiobutton is given below.

Syntax
w = Radiobutton (top, options)

The radiobutton widget provides the following methods.

Mr. D. S. Kiwde Page 18


MMN Python

SN Method Description

1 deselect() It is used to turn of the radiobutton.

2 flash() It is used to flash the radiobutton between its active and normal
colors few times.

3 invoke() It is used to call any procedure associated when the state of a


Radiobutton is changed.

4 select() It is used to select the radiobutton.

Example:
#radioButton Demo
from tkinter import *

def selection():
selection = "You selected the option " + str(radio.get())
label.config(text = selection)

top = Tk()
top.geometry("300x150")
top.title('MainPage')
radio = IntVar()
lbl = Label(text = "Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,
command=selection)
R1.pack(anchor = W)
R2 = Radiobutton(top, text="C++", variable=radio, value=2,
command=selection)
R2.pack( anchor = W )
R3 = Radiobutton(top, text="Java", variable=radio, value=3,
command=selection)
R3.pack( anchor = W)
label = Label(top)
label.pack()
top.mainloop()

Mr. D. S. Kiwde Page 19


MMN Python

Checkbutton

 The Checkbutton is used to track the user's choices provided to the


application.
 In other words, we can say that Checkbutton is used to implement the
on/off selections.
 The Checkbutton can contain the text or images.
 The Checkbutton is mostly used to provide many choices to the user
among which, the user needs to choose the one.
 It generally implements many of many selections.

The syntax to use the checkbutton is given below.

Syntax

w = checkbutton (master, options)

Example:
#checkButton Demo
from tkinter import *

top = Tk()

top.geometry("200x200")

checkvar1 = IntVar()

checkvar2 = IntVar()

checkvar3 = IntVar()

Mr. D. S. Kiwde Page 20


MMN Python

chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1, onvalue


= 1, offvalue = 0, height = 2, width = 10)

chkbtn2 = Checkbutton(top, text = "C++", variable = checkvar2,


onvalue = 1, offvalue = 0, height = 2, width = 10)

chkbtn3 = Checkbutton(top, text = "Java", variable = checkvar3,


onvalue = 1, offvalue = 0, height = 2, width = 10)

chkbtn1.pack()

chkbtn2.pack()

chkbtn3.pack()

top.mainloop()

4.4] Getting Input


 The Entry widget is used to provide the single line text-box to the user
to accept a value from the user.
 We can use the Entry widget to accept the text strings from the user.
 It can only be used for one line of text from the user.
 For multiple lines of text, we must use the text widget.

The syntax to use the Entry widget is given below.

Syntax
w = Entry (parent, options)

Mr. D. S. Kiwde Page 21


MMN Python

A list of possible options is given below.

SN Option Description

1 bg The background color of the widget.

2 bd The border width of the widget in pixels.

3 cursor The mouse pointer will be changed to the cursor type


set to the arrow, dot, etc.

4 exportselection The text written inside the entry box will be


automatically copied to the clipboard by default. We
can set the exportselection to 0 to not copy this.

5 fg It represents the color of the text.

6 font It represents the font type of the text.

7 highlightbackground It represents the color to display in the traversal


highlight region when the widget does not have the
input focus.

8 highlightcolor It represents the color to use for the traversal highlight


rectangle that is drawn around the widget when it has
the input focus.

9 highlightthickness It represents a non-negative value indicating the width


of the highlight rectangle to draw around the outside of
the widget when it has the input focus.

10 insertbackground It represents the color to use as background in the


area covered by the insertion cursor. This color will
normally override either the normal background for the
widget.

11 insertborderwidth It represents a non-negative value indicating the width


of the 3-D border to draw around the insertion cursor.
The value may have any of the forms acceptable to
Tk_GetPixels.

12 insertofftime It represents a non-negative integer value indicating


the number of milliseconds the insertion cursor should
remain "off" in each blink cycle. If this option is zero,

Mr. D. S. Kiwde Page 22


MMN Python

then the cursor doesn't blink: it is on all the time.

13 insertontime Specifies a non-negative integer value indicating the


number of milliseconds the insertion cursor should
remain "on" in each blink cycle.

14 insertwidth It represents the value indicating the total width of the


insertion cursor. The value may have any of the forms
acceptable to Tk_GetPixels.

15 justify It specifies how the text is organized if the text


contains multiple lines.

16 relief It specifies the type of the border. Its default value is


FLAT.

17 selectbackground The background color of the selected text.

18 selectborderwidth The width of the border to display around the selected


task.

19 selectforeground The font color of the selected task.

20 show It is used to show the entry text of some other type


instead of the string. For example, the password is
typed using stars (*).

21 textvariable It is set to the instance of the StringVar to retrieve the


text from the entry.

22 width The width of the displayed text or image.

23 xscrollcommand The entry widget can be linked to the horizontal


scrollbar if we want the user to enter more text then
the actual width of the widget.

Example
#Input Demo
from tkinter import *
top = Tk()
top.geometry("400x250")
top.title('MainPage')
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)

Mr. D. S. Kiwde Page 23


MMN Python

sbmitbtn = Button(top, text = "Submit",activebackground = "pink",


activeforeground = "blue").place(x = 30, y = 170)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()
Output:

4.5] Importing MySQL for Python

 Python needs a MySQL driver to access the MySQL database.


 In this tutorial we will use the driver "MySQL Connector".
 We recommend that you use PIP to install "MySQL Connector".
 PIP is most likely already installed in your Python environment.

Navigate your command line to the location of PIP, and type the
following:

 Now you have downloaded and installed a MySQL driver.

Test MySQL Connector

 To test if the installation was successful, or if you already have


"MySQL Connector" installed, create a Python page with the following
content:

Mr. D. S. Kiwde Page 24


MMN Python

demo_mysql_test.py:

import mysql.connector

 If the above code was executed with no errors, "MySQL Connector" is


installed and ready to be used.
4.6] Connecting with a database

In this section, we will discuss the steps to connect the python


application to the database.

There are the following steps to connect a python application to our


database.

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

 To create a connection between the MySQL database and the python


application, the connect () method of mysql.connector module is used.
 Pass the database details like HostName, username, and the database
password in the method call. The method returns the connection
object.

The syntax to use the connect () is given below.

Connection-Object = mysql.connector.connect (host = <hostname>,


user = <username> ,
passwd = <password> )

Consider the following example.

Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost",
user = "root",
passwd = "google")
Mr. D. S. Kiwde Page 25
MMN Python

#printing the connection object


print(myconn)

Output:

<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>


 Here, we must notice that we can specify the database name in the
connect () method if we want to connect to a specific database.

Example
import mysql.connector

#Create the connection object


myconn = mysql.connector.connect(host = "localhost",
user = "root",passwd = "google", database = "mydb")

#printing the connection object


print(myconn)

Output:

<mysql.connector.connection.MySQLConnection object at 0x7ff64aa3d7b8>

Mr. D. S. Kiwde Page 26

You might also like