Graphical User Interface in Python
Graphical User Interface in Python
Interface in Python
Introduction to USER INTERFACE
User can interact with the application in two ways.
1.Using command ( to print a document PRINT command)(CUI)
Drawback : remembering of commands is difficult
2.Interact with application using graphics, pictures or images(GUI)
Advantages:
1.user friendly
2.Makes application more attractive due to which application gains
popularity
3. Simulate the real life object hence eliminates the need of user
training
GUI in python
Python offers tkinter module to create a graphics program. tkinter
represents the toolkit interface for GUI. This module enables the
programmers to use the classes of TK module of TCL/TK language. TCL
is tool command language and is dynamic language suitable for
web,desktop, networking applications. It is open source. TCL uses
TK(tool kit) language to generate graphics. TK provide GUI not only for
TCL also for python. Hence TK is user by programmers in developing
GUI applications through tkinter module.
Steps involved in basic GUI
programs
1. First create a root window and is the top level window which provides
a rectangular space on a screen where we can display
text,color ,images,components etc.
2. In the root window we have to allocate space for our use. This is done
by creating a canvas or frame. Canvas or frame are called as child
windows in the root window
3. Canvas are used for displaying shapes such as line, circle, arcs etc.
Frame for displaying components like push, radio, check buttons,
menus etc. These components are called as widgets
4. When user clicks the widgets placed on frame then event occurs and
we have to handle the event by performing specific task through code.
Root window
To display the graphical output we need space on the screen and this
space is allocated to every GUI program is called root window or top
level window. This is highest level GUI component in any tkinter
applications.
Python program to create a root window or top level window
Filename:g1.py
To create a root window first we should import toolkit interface module
available in python which contains main classes through which we can
create GUI in python. After importing create a object of class Tk. Where
Tk() is constructor. Now r is the object of the class. r.mainloop()
executes the program continues until user closes the root window.
continued
In second program root window is created by setting the properties
such as size,background color,title for window and changing the
window icon. r.title() is used to change the title to my Window by
default it is tk. r.geometry() changes the window size and is mentioned
in terms of pixel. R.configure(bg=’ ‘) set the background color.
r.wm_iconbitmap('image1.jpg') will make the change in the window
icon by default it is a feather.
Python program to create root window by giving name, altering the size
and background color
Filename:g2.py
Working with Container:
A container is component that is used as a place where drawings or
widgets can be displayed. A container is a space that displays the output to
the user. There are two important containers
Canvas: used to draw shapes like lines, curves, arcs and circles
Frame: used to display widgets likes buttons, textbox, labels etc.
To create a frame we create object of Frame class as
F=Frame(root,height=400,width=300,bg=‘yellow’,cursor=‘cross’)
F is object of frame class and is created as a child of ‘root’ window. The
options height and width represents the size of frame in pixels. Bg
represents the background color and cursor represents the type of the
cursor
Frame object f is added to the root window using pack() method as f.pack()
Python program to create a frame on root window
Filename:g3.py
Widgets
A widget is a GUI component that is displayed on the screen and can perform a task as desired by user.
We create widgets as objects. For example a push button is a widget that is object of class Button. Once a
widget is created it should be added to frame. The following are the important widgets in python
•Button
•Label
•Message
•Text
•Scrollbar
•Checkbutton
•Radiobutton
•Entry
•Spinbox
•Lsitbox
•Menu
continued
In general working with widgets takes the following four steps:
1. Create the widgets that are needed in the program. Widget is a GUI component that
is represented as an object of a class. For example a push button is a widget that is
represented as object of a class Button.
b=Button(f,text=‘My Button’,
width=15,height=2,bg=’yellow’,fg=’blue’,activebackground=’green’,activeforeground=’
red’)
b is the object of class Button. f represents the frame to which button object is added
and button is a child of a frame. The text option represents the text to be displayed on
the button. Width and height represent the size of the button.bg represent the
background color and fg represents the text color on button. active background is
about background color when button is clicked.
continued
2.When the user interacts with a widget, it will generate an event.
Clicking the button is an event. Such an event is handled by writing
function. These functions are called event handlers or callback
handlers.
As an example lets write a function that may be called in response to
button click
Def buttonClick(self):
Print(“you have clicked me’)
continued
3.When the user clicks on the push button that clicking event should be
linked with event handler function. This is done with the following
function bind()
b.bind(‘<Button-1>’, buttonClick)
b represent the push button object, <Button-1> indicates the left
mouse button. When the user presses the left mouse button the
buttonClick function is called.
continued
4.The above three steps make the widgets ready for the user. Now the
user should run the program and interact with the widget by pressing
mouse button or entering text. These events are continuously
monitored by our program with the help of loop
r.mainloop()
r is the object of root window. The events in the root window is
continuously observed by the mainloop() method.
Button Widget
Python program to create a push button and bind it with an event
handler function
Filename:g4.py
Second way to create push button is using class concept
Python program to create a push button and bind it with an event
handler function using class and command option
Filename:g5.py
Creating several buttons
When we create the several buttons, we need to know which button is clicked by
the user. This will help us to perform the task depending on the button clicked. In
this case we have to call the event handler function by passing some argument that
represents which button is clicked. For example
B1=Button(f,text=’My Button’ width=12,height=2,command=lambda:click(1))
Command=lambda:click(arg1,arg2,….)
Command option will not allows to mention the method name only and is not
possible to pass arguments to the method. Suppose we want to pass arguments,
then we need to use lambda expression as show above
continued
python program to create 3 button by name red green
and blue. When user clicks a button background color of
the frame will change according to the button clicked
(using class concept)
Filename:g6.py
filename:g9.py
Message Widget
Filename:g13.py
Spinbox Widget
A spinbox widget allows the user to select values from a given set of values. The
values may be range of numbers or fixed set of strings.
The spinbox appears as long rectangle attached with arrowheads pointing towards
up and down. The user click on the arrowheads to see the next value or previous
value. The user can also edit the value being displayed in the spin box just like we
can do in entry widget.
A spinbox is created as an object of Spinbox class. To create a spin box with
numbers ranging from 5 to 15 we can write the following statement
S=Spinbox(f,from_=5,
to=15,textvarible=val1,width=15,fg=’blue’,bg=’yellow’font=(‘Arial’,14,’bold’))
continued
•S is spinbox object
•f represent the parent widget
•from_ indicates the starting value and to indicates the ending value in the spin box
•text variable represents an object of IntVar() class. The object of the IntVar is
created as shown below.
•Var1=IntVar()
•Var1 is a control variable that receives the displayed value in the spin box.
•fg=foreground color
•bg=background color
•font =font type size and style
continued
We can create a spin box with strings by specifying the strings as a tuple as
shown in the following statement:
S1=Spinbox(f,
values=(‘Delhi’,’Bombay’,’Bagalkot’,’Bangalore’),textvarible=val2,width=15,fg=
’blue’,bg=’yellow’font=(‘Arial’,14,’bold’))
The fixed strings that are displayed in the spin box are mentioned in the
values option as a tuple as shown below
values=(‘Delhi’,’Bombay’,’Bagalkot’,’Bangalore’)
continued
The text variable option indicates the control variable value val2 that is
created as an object of StringVar class as shown below
Val2=StringVar()
Val2 contains the displayed string in the spinbox. To retrieve the values from
the control variables using get method
a=val1.get() #get the number from val1
b=val2.get() #get the number from val2
python program to create two spin boxes and retrieve the values
displayed in the spin boxes when the user clicks on push button
Filename:g14.py
Listbox Widget
A listbox is useful to display a list of items in a box that the user
can select 1 or more items. To create a list box, we have to
create an object of Listbox class as:
l=Listbox(f,
font=(‘Arial’,14,’bold’),fg=’blue’,bg=’yellow’,height=8,width=24,
activestyle=’underline’,selectmode=MULTIPLE)
•l is listbox object
•f represent the parent widget
•font =font type size and style
continued
•fg=foreground color
•bg=background color
•Height represents height of widget
•Width represents width of widget
•Activestyle indicates the appearance of the selected item. It may be
‘underline’, ‘dotbox’ or ‘none’. The default value is ‘underline’.
continued
•Selectmode may take any of the following values
•BROWSE: Normally we can select one item out of a list box. If we click on an item
and then drag to a different item, the selection will follow the mouse. This is the
default value of select mode
•SINGLE: This represents that we can select only one item from all available list of
items
•MULTIPLE: We can select 1 or more number of items at once by clicking on the
items. If an item is already selected clicking second time on the item will un select
it
•EXTENDED: We can select any adjacent group of items at once by clicking on the
first item and dragging to the last item.
continued
•Once the listbox is created, we should insert items into the listbox using insert()
method as
•City= city=['delhi','Bombay','Belagum','Bangalore','Managlore','Mysore','Hubli']
•for i in city:
• l.insert(END,i)
•Here the first argument END represents that the text is added at the end of the
previous text
•To bind the ListboxSelect event with a method, we can use the bind method as:
•l.bind(‘<<ListboxSelect>>’, display)
continued
when user selects any item in the listbox, the method display will be called. This
method can be written as below:
def display(self):
#create an empty list
sc=[]
#know the indexes of the selected items
p=l.curselection()
#retrieve the items names depending on indexes append the items names to the list
for i in p:
sc.append(l.get(i))
continued
python program to create a list box with city names and display
the selected cities names in text box
Filename:g15.py
Text Widget
Text widget is same as a label or message. But text widget has several options and
can display multiple lines of text in different colors and fonts. It is possible to insert
text into a text widget, modify it or delete it. We can also display images in the text
widget. We can create a text widget using Text class
T=Text(f,width=20,height=10,font=(‘Verdana,14,’bold’),fg=’blue’,bg=’blue’,wrap=W
ORD)
f represent the parent widget
font =font type size and style
fg=foreground color
Continued
bg=background color
Height represents height of widget
Width represents width of widget
Wrap represents where to cut the lines. WRAP=CHAR represents that
any line that is too long will be broken at any character
Wrap=WORD will break the line in the widget after the last word that
fits in the line
Wrap=NONE will not wrap the lines
continued
Python Program to enter your name using text widget and display it
using entry widget.
Scrollbar Widget:
A scrollbar is a widget that is useful to scroll the text in another widget. There are
two types of scroll bars. They are horizontal and vertical. Horizontal scroll bar is
useful to view the text from left to right. Vertical scroll bar is useful to scroll the text
from top to bottom. To create a scroll bar object we use scrollbar class as shown
below
H=Scrollbar(f,orient=HORIZONTAL,bg=’green’)
H represent the Scrollbar object
f represent parent of H
orient represents HORIZONTAL scrollbar and VERTICAL represents vertical scrollbar
bg represents background color
continued
After creating the scroll bar, it should be attached to the widget like text
widget or listbox as:
H.configure(command=t.xview)
t is the object of text widget and while creating text widget we must
pass option xscrollcommand and must be set to H.set inorder to call
the set() method of horizontal scroll bar
continued
python program to create horizontal scroll bar and attach it to a text
widget to view the text from left to right
Filename:g16.py
continued
similarly we can create a vertical scroll bar v as shown below
v=Scrollbar(f,orient=VERTICAL,bg=’green’)
After creating the scroll bar, it should be attached to the widget like text widget
or listbox as:
v.configure(command=l.yview)
l is the object of listbox and while creating listbox widget we must pass option
yscrollcommand and assign v.set to calls the set() method of vertical scroll bar
Canvas is rectangular area which can be used for drawing pictures like lines, circles,
polygons, arcs etc. To create an object of canvas class
C=Canvas(root,bg=”blue”, height=500,width=600,cursor=’pencil’)
Root is the name of parent window
Bg is background color
Width and height is the size
Cursor represents the shape of cursor in the canvas
Once canvas object is created it is added to root window using pack() method
c.pack()
continued
l=c.create_line(50,50,100,100,width=4,fill=”black”)
this creates a line by connecting the points(50,50) and (100,100). Width specifies the width of the
line and fill specifies the color
o=c.create_oval(100,100,400,300,width=5,fill=”yellow”,outline=”red”,activefill=”green”)
creates an oval with top left corner(100,100) and bottom lower corner(400,300). Outline shows the
border color. Activefill the color to be filled in oval when mouse is placed on oval
Same way following statements will create a polygon, rectangle and text
P=c.create_polygon(10,10,200,200,300,200,width=3,fill=”green”,outline=”red”,activefill=”blue”)
R= c.create_rectangle(10,10,200,200,width=3,fill=”green”,outline=”red”,activefill=”blue”)
T=c.create_text(10,10,text=”hello”,font =(“Times”,40,”bold”),
width=3,fill=”green”,ourline=”red”,activefill=”blue”)
continued
python program to display drawing in the canvas
Filename:g20.py