Unit Iii: Graphical User Interface
Unit Iii: Graphical User Interface
• Output:
• Label Widget
• A label represents constant text that is displayed in the frame or container.
• A label can display one or more lines of text that cannot be modified.
• A label is created as an object of Label class as:
lbl = Label(f, text=”text to be displayed”, width=m, height=n, font=('font
nae', msize, “style‟), fg=‟color‟, bg=‟color‟)
lbl = Label(f, text="Welcome to Python", width=20, height=2,
font=('Courier', -30, “bold underline‟), fg=‟blue‟, bg=‟yellow‟)
• Here, f represents the frame object to which the label is created as a child.
• 'text' represents the text to be displayed.
• “width‟ represents the width of the label in number of characters and
'height' represents the height of the label in number of lines.
• “font‟ represents a tuple that contains font name, size and style.
• ‘fg’ and 'bg' represents the foreground and background colors for the text.
• Label is created in the event handler method buttonClick() that is bound to
the first button.
• We display another button 'Close' that will close the root window upon
clicking
• The close button can be created as:
• B1= button(f, text=‟Close‟ , width=15, height=2, command=quit)
• Please observe the “command‟ option that is set to 'quit'. This represents
closing of the Root window.
• A Python program to display a label upon clicking a push button.
• from tkinter import*
class MyButtons:
• #constructor
def __init__(self, root):
• #Create a frame as child, to root window
self.f = Frame(root, height-350, width=500)
• #let the frame will not shrink
self.f.propagate (0)
• #attach the frame to root window
self.f.pack()
• #create a push button and bind it to buttonClick() method
self.b1=Button(self.f, text=‟Click Me‟, width=15, height=2,
command=self.buttonClick)
• # create another button that closes the root window upon clicking
self.b2 = Button(self.f, text=‘Close', width=15, height=2,
Command=quit)
• # attach buttons to the frame
self.b1.grid(row=0, column=1)
self.b2.grid(row=0, column=2)
• #the event handler method
def buttonClicK(self):
• #create a label with some text
self.lbl= Label(self.f, text=”welcome to Python”, width=20,height=2,
font=( “Courier‟, -30, “bold underline‟) , fg=‟blue‟)
• #attach the label in the frame
self.lbl.grid(row=2, column=0)
• # create root window
root =Tk()
• #create an object to MyButtons class
mb= MyButtons (root)
root.mainloop()
• Message Widget
• A message is similar to a label.
• But messages are generally used to display multiple lines of text where as a
label is used to display a single line of text.
• All the text in the message will be displayed using the same font.
• To create a message, we need to create an object of Message class as:
Message (f,text =‟Displaytext‟,width=m, font=(“Fontname‟, size,
“fontstyle‟), fg=‟color‟)
Message (f, text= "This is a message that has more than one line of text.'
width=200, font=('Roman', 20, 'bold italic'), fg='dark goldenrod’)
• Here, text represents the text to be displayed in the message.
• The width option specifies the message width in pixels. “font‟ represents the
font for the message.
• We can use options fg for specifying foreground color and bg for specifying
background color for the message text.
• Program: A Python program to display a message in the frame.
from tkinter import
class MyMessage:
def _init(self, root):
#create Frane as child to root window
self.f = Frame (root, height=350, width=500)
#let the frame will not shrink
self.f.propagate(0)
#attach the frame to root window
self.f.pack()
#create a Message widget with some text
self.m = Message(self.f, text=‟This is a message that has more than one
line of text.‟ width=200, font=(“Roman‟, 20, “bold italic‟), fg=‟darkgoldenrod”)
# attach Message to the frame
self.m.pack(side=LEFT)
# create root window
root = Tk()
# create an object to MyMessage class
mb = MyMessage(root)
root.mainloop()
• 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.
• One can create a Text widget by creating an object to Text class as:
t= Text (root, width=m, height=n, font=('fontname', size, 'fontstyle'),
fg='color‘, bg='color', wrap=WORD)
t = Text (root, width=20, height=10, font=('Verdana', 14, 'bold'), fg='blue' ,
bg='yellow', wrap=WORD)
• Here, ‘t’ represent object of Text classs, the 'root' represents an object of root
window or frame.
• ‘width' represents the width of the Text widget in characters. 'height'
represents the height of the widget in lines.
• The option ‘wrap' specifies where to cut the line.
• wrap=CHAR represents that any line that is too long will be broken at any
character.
• wrap=WORD will take the line in the widget after the last word that fits in the
line.
• wrap=NONE will not wrap the lines.
• In this case, it is better to provide a horizontal scroll bar to view the lines
properly in the Text widget.
• Once the Text widget is created, we can insert any text using the insert()
method as:
t.insert(END, “Text widget \nThis text is inserted into the text widget. \n
This is second line\n and this is third line\n‟)
• Here, the first argument END represents that the text is added at the end of
the previous text.
• We can also use CURRENT to represent that the text is added at the current
cursor position.
• The second argument is the text that is added to the Text widget.
• It is possible to display an image like a photo using the image_create()
method as;
img=PhotoImage(file=‟moon.gif‟) # store moon.gif into img object
t.image_create(END, image=self.img) #append img to Text widget at the end
• It is possible to display some part of the text as a tag and provide different
colors and font for that text.
• For this purpose, first we should specify the tag using the tag_add() method:
t.tag_add(“start‟,‟1.0‟, “1.11‟)
• Here, the tag name is 'start'.
• It contains characters (or text) from 1st row 0th character till 1st row 11th
character.
• Now, we can apply colors and font to this tag text using the config() method:
t.tag_config(“start‟, background=‟red‟, foreground=‟white‟, font (“Lucida
console‟, 20,‟ bold italic‟))
• Here, we are applying 'red' background and ‘white' foreground and 'Lucida
console” font to the text that is already named as 'start' tag.
• In this way, we can have several tags in the Text widget.
• In many cases, it is useful to add scroll bars to the Text widget.
• A scroll bar is a bar that is useful to scroll the text either horizontally or
vertically.
• For example, we can create a vertical scroll bar by creating an object to Scroll
bar class as:
s = Scrollbar (root, orient=VERTICAL, command= t.yview)
• Here, 'orient' indicates whether it is a vertical scroll bar or horizontal scroll
bar.
• The “command‟ option specifies to which widget this scroll bar should be
connected.
• t.yview represents that the scroll bar is connected to “t‟, i.e. Text widget and
“yview‟ is for vertical scrolling.
t.configure(yscrollcommand=s.set)
• We should set the ‘yscrollcommand' option of the Text widget ‘t' to 's.set'
method.
• In this way, the scroll bar 's' is connected to Text widget t.
• Program: A Python program to create a Text widget with a vertical scroll bar
attached to it. Also, highlight the first line of the text and display an image in
the Text widget.
from tkinter import*
class MyText:
• #constructor
def __init__(self, root):
• # create a Text widget with 20 chars width and 10 lines height
self.t= Text (root, width=20, height=10, font=(“Verdana‟,
14,”bold‟), fg=‟blue‟, bg=‟yellow‟, wrap=WORD)
• #insert some text into the Text widget
self.t.insert(END, “Text widget\n This text is inserted into the
Text widget.\n This is second line \n and this is third line \n”)
• # attach Text to the root
self.t.pack(side=LEFT)
• # show image in the Text widget
self.img = PhotoImage(file='moon.gif')
self.t.image_create(END, image=self.img)
• # create a tag with the name 'start'.
self.t.tag_add(“start‟, „1.0‟, „1.11‟)
• # apply colors to the tag
self.t.tag_config(“start‟,foreground=”white”, Font=(“Lucida console”,
20, “bold italic”))
• # create a Scrollbar widget to move the text vertically
self.s = scrollbar(root, orient=VERTICAL, command=self.t.yview)
• # attach the scroll bar to the Text widget
self.t.configure(yscrollcommand=self.s.set)
• # attach the scroll bar to the root window
self.s.pack(side=RIGHT, fill=Y)
• # create root window
root = Tk()
• # create an object to MyText class
mt = MyText(root)
• # the root window handles the mouse click event
root.mainloop()
from tkinter import *
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow",
foreground="blue") text.tag_config("start",
background="black", foreground="green") root.mainloop()
• Scrollbar Widget
• A scroll bar is a widget that is useful to scroll the text in another widget.
• For example, the text in the Text, Canvas, Frame or Listbox can be scrolled
from top to bottom or left to right using scroll bars.
• There are two types of scroll bars. They are horizontal and vertical.
• The horizontal scroll bar is useful to view the text from left to right.
• The vertical scroll bar is useful to scroll the text from top to bottom.
• To create a scroll bar, we have to create Scrollbar class object as:
h=Scrollbar (root, orient=HORIZONTAL, bg=‟green‟, command=t.xview)
• Here, ‘h' represents the scrollbar object which is created as a child to 'root'
window.
• The option ‘orient' indicates HORIZONTAL for horizontal scroll bars and
VERTICAL indicates vertical scroll bars.
• ‘bg' represents back ground color for the scroll bar.
• This option may not work in Windows since Window operating system may
force some default background color for the scroll bar which will not be
disturbed by the tkinter.
• The option “command‟ represents the method that is to be executed.
• The method ‘xview' is executed on the object t.
• Here, t may represent a widget like Text widget or Listbox.
• Similarly, to create a vertical scroll bar ‘v', we can write:
v=scrollbar(root, orient=VERTICAL, bg=‟green‟, command=t.yview)
• After creating the scroll bar, it should be attached to the widget like Text
widget or Listbox as:
t.configure (xscrollcommand=h.set)
• Here, t' indicates Text widget. xscrollcommand calls the set() method of
horizontal scroll bar.
• In the same way, we can attach vertical scroll bar as:
t.configure(yscrollcommand=v.set)
• Finally, the scroll bar should be attached to the root window using the pack()
or grid() methods as:
h.pack(side=BOTTOM, fill=X)
• Here, we are attaching the horizontal scroll bar at the bottom of the widget
and it spreads across X axis.
• Similarly, to attach vertical scroll bar, we can use the following statement:
• v.pack(side-RIGHT, fill=Y)
• Program: A Python program to create a horizontal scroll bar and attach it to
a Text widget to view the text from left to right.
• from tkinter import*
• class MyScrollbar:
• # constructor
def __init__(self, root):
• # create a Text widget with 70 chars width and 15 lines height
self.t= Text (root, width=70, height=15, wrap=NONE)
• # insert some text into the Text widget
for i in range(50):
self.t.insert (END, "There is my text to insert")
• # attach Text widget to root window at the top
self.t.pack(side=TOP, fill=X)
• # create a horizontal scroll bar and attach it to Text widget
self.h = Scrollbar(root, orient=HORIZONTAL,command=self.t.xview)
• # attach Text widget to the horizontal scroll bar
self.t.configure(xscrollcommand=self.h.set)
• # attach Scrollbar to root window at the bottom
self.h.pack(side=BOTTOM, fill=X)
• # create root window
root = TK()
• # create an object to MyScrollbar class
ms = MyScrollbar(root)
• # the root window handles the mouse click event
root.mainloop()
• Checkbutton Widget
• Check buttons, also known as check boxes are useful for the user to select one
or more options from available group of options.
• Check buttons are displayed in the form of square shaped boxes.
• When a check button is selected, a tick mark is displayed on the button.
• We can create check buttons using the Checkbutton class as
c1= Checkbutton (f, bg=‟color‟, fg= 'color', font=("fontname”,
size,‟fontstyle‟), text=‟Any text‟. variables= var1, command= display)
• Here. “c1‟ is the object of Checkbutton class that represents a check button.
• “f” indicates frame for which the check button becomes a child and test
represent the background and fore ground colors used for check button .
• ‘font' represents the font name, size and style “text‟ represents the text to be
displayed after the check button.
• The option variable represents an object of IntVar() class "command"
represents the method to be called when the user clicks the check button
• The class “IntVar‟ is useful to know the state of the check button, whether it
is clicked or not.
• The IntVar class object can be created as:
var1 = IntVar()
• When the check button is clicked or selected, the value of “var1‟ be 1,
otherwise its value will be 0.
• To retrieve the value from var1, we should use the get() method, as
x = var1.get() #x value can be 1 or 0
• Program: A Python program to create 3 check buttons and know which
options are selected by the user
from tkinter import*
class MyCheck:
• #constructor
def __init__(self, root):
• #create a frame as child to root window
self.f = frame(root, height=350, width=500)
• #let the frame will not shrink
= self.f.propagate(0)
• #attach the frame to root window
self.f.pack()
• #create Intvar class variables
self.var1 = IntVar()
self.var2 = IntVar()
self.var3 = IntVar()
• #create check boxs and bind them to display method
self.c1= checkbutton(self.f, bg=‟yellow‟, fg=‟green‟, text=“Java”,
variable=self.var1, command=self.display)
self.c2 = checkbutton(self.f, text=‟Python‟,variable=self.var2,
command=self.display)
self.c3 = Checkbutton(self.f, text=”NET”, variable=self.var3,
command=self.display)
• # attach check boxes to the frame
self.c1.place(x=50, y=100)
self.c2.place(x=700, y=100)
self.c3.place(x=350, y=100)
def display (self):
• # retrieve the control variable values
x= self.var1.get()
y =self.var2.get()
z = self.var3.get()
• #string is empty initially
str =‟ “
• # catch user choice
if x==1:
str= "Java”
if y==1:
string=”Python”
if z ==1:
string=‟NET‟
• # display the user selection as a label
• lbl = Label(text=str, fg='blue').place(x=50, y=150, width=200,height=20)
• # create root window
root = Tk()
• # create an object to MyButtons class
mb = Mycheck(root)
• # the root window handles the mouse click event
root.mainloop()
• Output:
• Radiobutton Widget
• A radio button is similar to a check button, but it is useful to select only one
option from a group of available options.
• A radio button is displayed in the form of round shaped button.
• The user cannot select more than one option in case of radio buttons.
• When a radio button is selected, there appears a dot in the radio button.
• We can create a radio button as an object of the Radiobutton class as:
rl = Radiobutton(f, bg=‟color‟, fg= 'color', font=(“fontname‟, size,
“fontstyle”), text=‟text to display”', variable =var, value=1,
command=display)
r1 = Radiobutton(f, bg='yellow', fg= 'green',font=('Georgia', 20,'underline'),
text=‟Male‟ variable=var, value=1, command= display)
• The option text represents the string to be displayed after the radio button.
• variable represents the object of IntVar class.
• value represents a value that is set to this object when the radio button is
clicked.
• When the user clicks the radio button, the value of this ‘var‘ is set to the value
given in value option, i.e. 1.
• It means ‘var’ will become 1 if the radio button r1 is clicked by the user.
• In this way, it is possible to know which button is clicked by the user.
• Program: A Python program to create radio buttons and know which button
is selected by the user.
• from tkinter import *
class Myradio:
• #constructor
def __init__(self, root):
• # create a frame as child to root window
self.f = Frame (root, height=350, width=500)
• # let the frame will not shrink
self.f.propagate(0)
• #attach the frame to root window
self.f.pack()
• # create IntVar class variable
self.var = Intvar()
• #create radio buttons and bind them to display method
self.r1 = Radiobutton(self.f, bg='yellow', fg= 'green',font=('Georgia',
20,'underline'), text=‟Male‟, variable=self.var, value=1,
command=self.display)
self.r2 = Radiobutton(f, text='Female', variable self.var, value=2,
command=self.display)
• #attach radio buttons to the frame
self.r1.place(x=50, y=100)
self.r2.place(x=200, y=100)
def display(self):
• #retrieve the control variable value
x=self.var.get()
• #string is empty initially
str=‟ “
• #catch user choice
if x ==1:
str += “You selected: Male‟
if x==2:
str+= “You selected: Female‟
• #display the user selection as a label
lbl= Label(text=str, fg ='blue').place(x=50, y=150, width=200, height
=20)
• # create root window
root = Tk()
• # create an object to Mybuttons class
mb= Myradio(root)
• # the root window handles the mouse click event
root.mainloop()
• Output:
• Entry Widget
• Entry widget is useful to create a rectangular box that can be used to enter or
display one line of text.
• For example, we can display names, passwords or credit card numbers using
Entry widgets.
• An Entry widget can be created as an object of Entry class as:
• el=Entry(f, width=m, fg='color', bg='color', font=('fontname'. 14),show=‟*‟)
• Here, ‘el' is the Entry class object. ‘f’ indicates the frame which is the parent
component .
• For the Entry widget ‘width' represents the size of the widget in number of
characters.
• 'fg' indicates the fore ground color in which the text in the widget is displayed,
'bg' represents the back ground color in the widget.
• 'font' represents a tuple that contains font family name, size and style.
• 'show' represents a character that replaces the originally typed characters in
the Entry widget.
• For example, “show" is useful when the user wants to hide his password by
displaying stars in the place of characters.
• After typing text in the Entry widget, the user presses the Enter button. Such
an event should be linked with the Entry widget using bind() method as:
el.bind("<Return>") ,self.display)
• When the user presses Enter (or Return) button, the event is passed to
display() method.
• Hence, we are supposed to catch the event in the display method, using the
following statement:
def display (self, event):
• As seen in the preceding code, we are catching the event through an
argument 'event' in the display() method.
• This argument is never used inside the method.
• The method consists of the code that is to be executed when the user pressed
Enter button
• Program A Python program to create Entry widgets for entering user name
and password and display the entered text.
from tkinter import *
class MyEntry:
• # constructor
def __init__(self, root):
• # create a frame as child to root window
self.f = Frame (root, height=350, width=500)
• # let the frame will not shrink
self.f.propagate(0)
• # attach the frame to root window
self.f.pack ()
• # labels
self.l1= Label(text='Enter user name: ')
self.l2= Label(text='Enter Password: ')
• # create Entry widget for user name
self.e1= Entry(self. f, width=25, fg='blue', bg='yellow',
font=('Arial', 14))
• # create Entry widget for password. the text in the widget is replaced by stars (*)
self.e2 = Entry(self.f, width=25, fg='blue', bg='yellow',
show=‘*’)
self.e2.bind("<Return>", self.display)
• # place labels and entry widgets in the frame
self. 11.place(x=50, y=100)
self.e1.place(X=200, y=100)
self. 12.place(x=50, y=150)
self . e2.place(x=200, y=150)
def display(self, event):
• # retrieve the values from the entry widgets
str1 = self.el.get()
str2 = self.e2.get ()
• #display the values using labels
Lb1= Label(text='Your name is: +str1).place(x=50, y=200)
Lb2= Label(text='Your password is: '+str2).place(x=50,
y=220)
• # create root window
root = Tk()
• # create an object to MyButtons class
mb = MyEntry(root)
• # the root window handles the mouse click event
root.mainloop()
• Spinbox Widget
• A spinbox widget allows the user to select values from a given set of values.
• The values may be one of numbers of a set of strings
• The spin box appears as a long rectangle attached with arrow heads pointing
towards up and down.
• The user can 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 he can
do in case of an Entry widget
• A spin box is created as an object of Spinbox class.
s1= Spinbox(f, from_=x to=y, textvariable= val1,width= 15,fg='blue' ,
bg='yellow', font=('fontname', size, „fontface‟))
• Here, f represents the parent widget.
• ‘from_' indicates the starting value and “to‟ indicates the ending value in the
spin box.
• ‘textvariable shows the control variable, i.e. val1 that is created as an object
of the IntVar class, as follows:
val1 = IntVar()
• val1 is a control variable that receives the displayed value in the spin box.
• To create a spin box with numbers range from 1 to 15, we can write the
following statement:
s1= Spinbox(self.f,from_=1,to=15,textvariable=self.val1, width=15, fg='blue',
bg='yellow', font=('Arial',14,'bold'))
• Similarly, we can create a spin box with strings by specifying the strings as a
tuple as shown in the following statement:
s2=(f, values=(“Mangalore”,”Bangalore”,”Mysore”,”Hasan”), textvariable=val2,
width=15, width=15, fg='black' , bg=‟green‟, font=('Arial',14, 'bold italic'))
• Here, the fixed strings that are displayed in the spin box are mentioned in the
‘values' option as a tuple as shown in the following statement:
values=(“Mangalore”,”Bangalore”,”Mysore”,”Hasan”),
• The “textvariable” option indicates the control variable value ‘val2' that is
created as an object of StringVar() class as shown in the following statement:
val2 = StringVar()
• val2 contains the displayed string in the spin box. To retrieve the values from the
control variables, we can use the get() method as:
a = val1.get() #get the number from val1
s = val2.get() # get the string from val2
• Program: A Python program to create two spin boxes and retrieve the values
displayed in the spin boxes when the user clicks on a push button.
from tkinter import*
class MySpinbox:
• #constructor
def __init__(root,self):
• #create a frame as child to root windon
self.f=Frame(root, height=350, width=500)
• # let the frame will not shrink
self.f.propagate(0)
• #attach the frame to root window
self.f.pack()
• #these are control variables for Spinboxes
self.val1=IntVar()
self.val2 =StringVar()
• #create spinbox with numbers from 1 to 15
self.s1= Spinbox(self.f,from_=1,to=15,textvariable=self.val1,
width=15, fg='blue', bg='yellow',
font=('Arial',14,'bold'))
• # create spinbox with a tuple of strings
self.s2= Spinbox(self.f,
values=("Mangalore", "Bangalore", "Mysore", "Hasan"),
textvariable=self.val2,width=15, fg='black' ,bg='green',font=('Arial',14, 'bold
italic'))
• # createa button and bind it with display method
self.b= Button(self.f, text='Get values from spinboxes',
command=self.display)
• # place SpinLoxes and button widgets in the frame
self.s1place(x=50, y=50)
self.s2.place(x=50, y=100)
self.b.place(x=50, y=150)
def display(self):
• # retrieve the values from the Spinbox widgets
a = self.val1.get()
s = self.va12.get()
• #display the values using labels
lbl1 = Label(text='selected value is: '+str(a)).place(x=50,y=200)
lbl2 = Label(text='Selected city is: '+s).place(x=50, y=220)
• # create root window
root=Tk()
• # create an object to MySpinbox class
mb=MySpinbox(root)
• # the root window handles the mouse click event
root.mainloop()
• Listbox Widget
• A list box is useful to display a list of items in a box so that the user can select 1
or more items.
• To create a list box, we have to create an object of Listbox class, as:
lb = Listbox(f, font=”fontname” size „fontstyle‟ , fg='color', bg='color',
height=m,width=n, activestyle='underline', selectmode=MULTIPLE)
lb = Listbox(f, font="Arial 12 bold", fg='blue', bg='yellow', height=8, width=24,
activestyle='underline', selectmode=MULTIPLE)
• Here, lb is the list box object.
• The option 'height' represents the number of lines shown in the list box.
• width represents the width of the list box in terms of number of characters and
the default is 20 characters.
• The option 'activestyle' indicates the appearance of the selected item.
• It may be ‘underline', 'dotbox' or 'none'. The default value is ‘underline'.
• The option 'selectmode' may take any of the following values:
• BROWSE: Normally, we can select one item (or line) 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 'selectmode' option.
• SINGLE: This represents that we can select only one item( or line) 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.
• Once the list box is created, we should insert items into the list box using
insert() method as:
lb.insert(0, 'Standford University')
lb.insert(1, oxford University')
• To bind the ListboxSelect event with a method, we can use the bind() method
as:
lb.bind('<<ListboxSelect>>’, on_ select)
• The meaning of the previous statement is that when the user selects any
items in the list box, the method on_select() will be called.
• This method can be written something like this:
def on_select(event):
# create an empty list box
lst=[]
# know the indexes of the selected items
indexes = lb.curselection()
# retrieve the items names depending on indexes
# append the items names to the list box
for i in indexes:
lst.append(lb.get(i))