0% found this document useful (0 votes)
13 views18 pages

Graphical User Interface

A Graphical User Interface (GUI) allows users to interact with computers through visual elements like buttons and text boxes. Tkinter is a popular Python library for creating simple GUI applications, providing various widgets such as labels, buttons, and entry fields. The document also covers fundamental Tkinter concepts, including widget usage, geometry management, and layout organization.

Uploaded by

thirumalasarwad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views18 pages

Graphical User Interface

A Graphical User Interface (GUI) allows users to interact with computers through visual elements like buttons and text boxes. Tkinter is a popular Python library for creating simple GUI applications, providing various widgets such as labels, buttons, and entry fields. The document also covers fundamental Tkinter concepts, including widget usage, geometry management, and layout organization.

Uploaded by

thirumalasarwad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What Is A Graphical User Interface (GUI)?

Graphical User Interface (GUI) is nothing but a desktop application which helps you 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.

Python Libraries To Create Graphical User Interfaces:

There are many tool kit options available for developing graphical user interface
(GUI) . Most popular are given below:

 Kivy
 Python QT
 wxPython
 Tkinter

What Is Tkinter?

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:
Tkinter Widgets
Widget is a graphical user interface controls to interact between user and computer. Tkinter gives different types of
controls such as buttons, labels and text boxes used in a GUI application. Tkinter widgets are described in the following
table.

Widget Widget image Description

Canvas is a rectangle area which used to display


and edit graphics. For example – lines,
polygen, rectangle
Checkbutton Number of options can be selected using
check buttons. More than one choice can
be selected in grouped options
Entry A line of text can be entered using entry
widget
Frame A container to insert and organize other
widgets.
Label Caption of single line can be displayed
using label. Images may also insert to
label.

Listbox list of options can be provided listbox

Menubutton Menu options can be displayed in an


application.
Menu Various commands contained in Menu
buttons are given to user.
Message For displaying mulitline text fields to
take values from user
Radiobutton Only one option at a time can be
selected by Radio button.

Scale A number value can be changed by


moving knob of a slider.
Scrollbar Scrolling facility can be added for
various widegets.
Text Multiple line of text can be displayed.

Toplevel Separate window container can be


provided.
LabelFrame Works as a container for complex
window layouts.
tkMessageBox Message box can be inserted to
application.

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.

l1 = Label (window, text="edureka!“ font=("Arial Bold", 50))

[Link] (column=0, row=0)

Using Button widget in window


Function or a method can be attached to a button which is
called automatically when the button is clicked.
Here is the simple syntax to create this

widget: w = Button ( master,

option=value, ... ) Parameters:

 master: Parent window


 options: Options are listed in the Following table.
Option Description
Active Background color when the cursor is on the button.
background
Active Foreground color when the cursor is on the button.
foreground
Bd width of the border. Default is 2.
Bg Normal background color.
command Calling function or method when the button is clicked.
Fg Colour of the text (foreground)
Font Type of the font used for label of the button.
Height Height of the text or image
Highlight The color of the focus highlight when the widget has focus.
color
Image Image to be attached and display
Justify Alignment of the text line - justify
CENTER Alignment of the text line - center
Padx Horizontal length of button through x axis can be sat.
Pady vertical length of button through x axis can be sat.
Relief Border style- button appear as SUNKEN, RAISED, GROOVE,
or RIDGE
State Can set the button as DISABLED or ACTIVE. It active when
the button is over.
underline Underline the relevant character, Default is -1, which means no
character is underlined.
Width Set the width of the button.
wraplength If this value is set to a positive number, the text lines will be
wrapped to fit within this length.

Check out the code:

bt = Button (window, text="Enter", bg="orange", fg="red")

[Link] (column=1, row=0)

Output:

import Tkinter as tk
import tkMessageBox as bx

tp=[Link]( )

def exbutton( ):

[Link]("Python button example","Hello World")

B=[Link](tp,text="Press this button",command=exbutton)

[Link]( )

[Link]( )

Figure 14.3. Message “Hello World” will appear when "Press this button" is clicked
The output of the above program is shown in fig 14.3. When the button called
‘Press this button’ is clicked, the message box ‘Hello World’ will appear.

Using Entry widget in window


Single line text strings can be entered using entry widget. Text widget
can be used to enter multiple lines and label widget is used to display
one or more lines of text but cannot edit.
Syntax

Here is the simple syntax to create this widget −

w = Entry( master, option, ... )

Parameters:

 master: the parent window.


 options: : List of ususally used options are given below
Option Description
Bg background color
Bd Size of the border
The size of the border around the indicator. Default is 2
pixels.
command Invoking function when user change content
cursor Cursor of the mouse will change according to the given
cursor name (arrow, dot etc).
font Type of the font
exportselection By default, if you select text within an Entry widget, it is
automatically exported to the
clipboard To avoid this exportation, use exportselection=0.
Fg The color used to render the text.
highlightcolor The color of the focus highlight when the checkbutton has
the focus.
justify If the text contains multiple lines, this option controls how
the text is justified: CENTER, LEFT, or RIGHT.
relief With the default value, relief=FLAT, the checkbutton does
not stand out from its background. You may set this option
to any of the other styles .
Selectbackground Background color of the selected text

selectborderwidth The width of the border to use around selected text. The
default is one pixel.
selectforeground The foreground (text) color of selected text.

show Normally, the characters that the user types appear in the
entry. To make a .password. entry that echoes each
character as an asterisk, set show="*".
state The default is state=NORMAL, but you can use
state=DISABLED to gray out the control and make it
unresponsive. If the cursor is currently over the
checkbutton, the state is ACTIVE.
Width The default width of a checkbutton is determined by the
size of the displayed image or text. You can set this option
to a number of characters and the checkbutton will always
have room for that many characters.

Example 14.3. This program describes how to use a Tkinter entry in a program.

1 from Tkinter import *


2 tp=Tk()
3 la1=Label(tp,text="User ID")
4 [Link](side=LEFT)
5 en1=Entry(tp,bd=6)
6 [Link](side=RIGHT)
7 [Link]()
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 [Link] import *

2 combo = Combobox(window)

3 combo['values']= (1, 2, 3, 4, 5, "Text")

4 [Link](3)

[Link](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:

Another easy widget, done!

The next widget we will check on this Tkinter tutorial blog is the Checkbutton widget.

Checkbutton Widget:
The checkbutton is widely used in almost all the sites.
So basically we use the checkbutton class to create the widget.

Code snippet:

1 chk_state = BooleanVar()

2 chk_state.set (True)

3 chk = Checkbutton(window, text=‘Select', var=chk_state)

4 [Link](column=0, row=0)

We start by creating a variable of the type booleanvar.

But this is not a standard python variable, correct? Well nothing to worry, this is a Tkinter variable.

By default, we keep the set state to be true which means that the button is checked already. And
next, we are passing chk_state to the checkbutton class to set the check state for us.

Output:

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)

3 rad3 = Radiobutton(window, text=Scala', value=3)

4 [Link](column=0, row=0)

5 [Link](column=1, row=0)

[Link](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.

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


2 txt = [Link](window, width=40,height=10)
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 [Link] 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


2 [Link]('Message title’, 'Message content')
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():
2 [Link]('Message title', 'Message content')
3
4 btn = Button(window,text=‘ENTER', command=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:

Pretty easy, right?

Last but not least, we will check out the Spinbox widget on this Tkinter tutorial.
SpinBox Widget:
Spinbox is a popular widget as well. There are two tabs, the up and down scroll tabs present. This is
how it differs from the scroll down widget. Here the static number will change over a certain range of
values.

Code:

1 spin = Spinbox(window, from_=0, to=100, width=5)


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.
Organizing Layouts And Widgets
To arrange the layout in the window, we will use Frame, class. Let’s create a simple program to see
how the Frameworks.

Steps:-

 Frame creates the divisions in the window. You can align the frames as you like
with side parameter of pack() method.

 Button creates a button in the window. It takes several parameters like text (Value of the
Button), fg (Color of the text), bg (Background color)

Note – The parameter of any widget method must be where to place the widget.

In the below code, we use to place in the window, top_frame, bottom_frame.

1
import tkinter
2 window = [Link]()
3 [Link]("GUI")
4 # creating 2 frames TOP and BOTTOM
5 top_frame = [Link](window).pack()
bottom_frame = [Link](window).pack(side = "bottom")
6 # now, create some widgets in the top_frame and bottom_frame
7 btn1 = [Link](top_frame, text = "Button1", fg = "red").pack()# 'fg - foreground' is
8 btn2 = [Link](top_frame, text = "Button2", fg = "green").pack()# 'text' is used to
9 btn3 = [Link](bottom_frame, text = "Button2", fg = "purple").pack(side = "left")#
10 widgets
btn4 = [Link](bottom_frame, text = "Button2", fg = "orange").pack(s
11 [Link]()
12
Above code produces the following window, if you didn’t change the above code.

See the below example to get an idea of how it works.

1 import tkinter
window = [Link]()
2
[Link]("GUI")
3 # creating 2 text labels and input labels
4 [Link](window, text = "Username").grid(row = 0) # this is place
5 # 'Entry' is used to display the input-field
6 [Link](window).grid(row = 0, column = 1) # this is placed in
[Link](window, text = "Password").grid(row = 1) # this is place
7 [Link](window).grid(row = 1, column = 1) # this is placed in
8 # 'Checkbutton' is used to create the check buttons
9 [Link](window, text = "Keep Me Logged In").grid(columnspan = 2) # 'columnspan'
10 columns
11 # you can also use 'rowspan' in the similar manner
12 [Link]()
13
You will get the following output:

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 = [Link]()
3 [Link]("GUI")
4 # creating a function called say_hi()
5 def say_hi():
6
7 [Link](window, text = "Hi").pack()
[Link](window, text = "Click Me!", command = say_hi).pack() # 'command' is execute
8 # in this above case we're calling the function 'say_hi'.
9 [Link]()
10
The above program will produce the following results:

Another way to bind functions is by using events. Events are something like mousemove,
mouseover, clicking, and scrolling.
The following program also produces the same output as the above one:

1
2 import tkinter
window = [Link]()
3 [Link]("GUI")
4 # creating a function with an arguments 'event'
5 def say_hi(event): # you can rename 'event' to anything you want
6
7 [Link](window, text = "Hi").pack()
btn = [Link](window, text = "Click Me!")
8 [Link]("Button-1", say_hi) # 'bind' takes 2 parameters 1st is 'event' 2nd is 'func
9 [Link]()
10 [Link]()
11

 ‘<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
2 import tkinter
3 window = [Link]()
4 [Link]("GUI")
#creating 3 different functions for 3 events
5 def left_click(event):
6
7 [Link](window, text = "Left Click!").pack()
8 def middle_click(event):
9
10 [Link](window, text = "Middle Click!").pack()
def right_click(event):
11
12 [Link](window, text = "Right Click!").pack()
13 [Link]("Button-1", left_click)
14 [Link]("Button-2", middle_click)
15 [Link]("Button-3", right_click)
16 [Link]()
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.

Images And Icons


You can add Images and Icons using PhotoImage method.

Let’s how it works:

1
import tkinter
2 window = [Link]()
3 [Link]("GUI")
4 # taking image from the directory and storing the source in a variable
5 icon = [Link](file = "images/[Link]")
6 # displaying the picture using a 'Label' by passing the 'picture' variriable to 'imag
label = [Link](window, image = icon)
7 [Link]()
8 [Link]()
9
You can see the icon in the GUI:

Now, you’re able to:-

 Understand the Tkinter code.


 Create frames, labels, buttons, binding functions, events and all.
 To develop simple GUI apps.

So next up on this Tkinter Tutorial blog, we’re going to create a simple Calculator GUI with all the
stuff that we’ve learned till now.
Use – Case : Calculator App Using Tkinter
Every GUI apps include two steps:

 Creating User Interface

 Adding functionalities to the GUI

1 from tkinter import *


# creating basic window
2
window = Tk()
3 [Link]("312x324") # size of the window width:- 500, heigh
4 [Link](0, 0) # this prevents from resizing the wind
5 [Link]("Calcualtor")
6 ################################### functions ##########################
# 'btn_click' function continuously updates the input field whenever you e
7 def btn_click(item):
8
9 global expression
10
11 expression = expression + str(item)
12
13 input_text.set(expression)
# 'btn_clear' function clears the input field
14 def btn_clear():
15
16 global expression
17
18 expression = ""
19
20 input_text.set("")
21
# 'btn_equal' calculates the expression present in input fiel
22
23 def btn_equal():
24
25 global expression
26
27 result = str(eval(expression)) # 'eval' function evalutes the string exp
28
29 # you can also implement your own function to evalute the expression istead
30
input_text.set(result)
31
32 expression = ""
33
34 expression = ""
35
36 # 'StringVar()' is used to get the instance of input field
37
38 input_text = StringVar()
39
# creating a frame for the input field
40
41 input_frame = Frame(window, width = 312, height = 50, bd = 0, highlightbackground = "black
42 highlightthickness = 1)
43
44 input_frame.pack(side = TOP)
45
# creating a input field inside the 'Frame'
46
47 input_field = Entry(input_frame, font = ('arial', 18, 'bold'), textvariable = input_text, w
48 justify = RIGHT)
49
50 input_field.grid(row = 0, column = 0)
51
52 input_field.pack(ipady = 10) # 'ipady' is internal padding to increase the hei
53
54 # creating another 'Frame' for the button below the 'input_fra
55
btns_frame = Frame(window, width = 312, height = 272.5, bg = "gre
56
57 btns_frame.pack()
58
59 # first row
60
61 clear = Button(btns_frame, text = "C", fg = "black", width = 32, height = 3, bd = 0, bg = "#e
62 = lambda: btn_clear()).grid(row = 0, column = 0, columnspan = 3, padx = 1
63
64 divide = Button(btns_frame, text = "/", fg = "black", width = 10, height = 3, bd = 0, bg = "#
65 = lambda: btn_click("/")).grid(row = 0, column = 3, padx = 1, pady
66
67 # second row
68
seven = Button(btns_frame, text = "7", fg = "black", width = 10, height = 3, bd = 0, bg = "#f
69
= lambda: btn_click(7)).grid(row = 1, column = 0, padx = 1, pady
70
71 eight = Button(btns_frame, text = "8", fg = "black", width = 10, height = 3, bd = 0, bg = "#f
72 = lambda: btn_click(8)).grid(row = 1, column = 1, padx = 1, pady
73
74 nine = Button(btns_frame, text = "9", fg = "black", width = 10, height = 3, bd = 0, bg = "#ff
75 lambda: btn_click(9)).grid(row = 1, column = 2, padx = 1, pady =
76
77 multiply = Button(btns_frame, text = "*", fg = "black", width = 10, height = 3, bd = 0, bg
78 command = lambda: btn_click("*")).grid(row = 1, column = 3, padx = 1,
79
80 # third row
81
four = Button(btns_frame, text = "4", fg = "black", width = 10, height = 3, bd = 0, bg = "#ff
82
lambda: btn_click(4)).grid(row = 2, column = 0, padx = 1, pady =
83
84 five = Button(btns_frame, text = "5", fg = "black", width = 10, height = 3, bd = 0, bg = "#ff
85 lambda: btn_click(5)).grid(row = 2, column = 1, padx = 1, pady =
86
87 six = Button(btns_frame, text = "6", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff
88 lambda: btn_click(6)).grid(row = 2, column = 2, padx = 1, pady =
89
90 minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0, bg = "#e
91 = lambda: btn_click("-")).grid(row = 2, column = 3, padx = 1, pady
92
93 # fourth row
94
95 one = Button(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff
lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1, pady =

two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff


lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady =
96
97 three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0, bg = "#f
98 = lambda: btn_click(3)).grid(row = 3, column = 2, padx = 1, pady
99
100 plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0, bg = "#ee
101 lambda: btn_click("+")).grid(row = 3, column = 3, padx = 1, pady
102
# fourth row
103
104 zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg = "#ff
105 lambda: btn_click(0)).grid(row = 4, column = 0, columnspan = 2, padx = 1
106
107 point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0, bg = "#e
108 = lambda: btn_click(".")).grid(row = 4, column = 2, padx = 1, pady
109
equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0, bg = "#
= lambda: btn_equal()).grid(row = 4, column = 3, padx = 1, pady =

[Link]()

You might also like