Module5 Python GUI
Module5 Python GUI
tkinter also offers access to the geometric configuration of the widgets which can
organize the widgets in the parent windows. There are mainly three geometry
manager classes class.
1.pack( ) method:It organizes the widgets in blocks before placing in the parent
widget.
2.grid( ) method:It organizes the widgets in grid (table-like structure) before placing
in the parent widget.
3.place( ) method:It organizes the widgets by placing them on specific positions dir
ected by the programmer.
Tkinter widgets
Tkinter provides various controls such as button,label and text boxes used in a GUI
applications.These controls are commonly called Widgets.There are several types of
widgets in Tkinter.
Some of the major widgets are explained below:
4 EntryThe Entry widget is used to display a single-line text field for accepting
values from a user.
Label Widget
A Label is a tkinter widget class.It refers to the display box where you can put any
text or image .The label is widget that the user just views but not interacts with.The
text displayed by this widget can be updated at any time we want.
The general syntax is:
w=Label(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
1.anchor : It controls where the text is positioned if the widget has more space than
the text needs.
2. bg: to set he normal background color displayed behind the label.
3.bd :Size of the border around the indicator.Default is 2 pixels.
4.cursor:set the mouse cursor pattern when it is over the text.
5.font: If we are displaying text in this label(using text or textvariable option), the
font option specifies in what font that text will be displayed.
6.text: To display one or more lines of text in a label widget, set this option to a
string containing the text.Internal newlines (“\n”)will force a line break.
7.textvariable:also used to set the text to be displayed.When the variable changes,
the text of the widget also changes.For this set this option to the StringVar().
from tkinter import *
top = Tk()
l1= Label(top, text="Hello World")
l1.pack()
top.mainloop()
Entry Widget
It is used to input the single line text entry from the user.It is the basic widget of
tkinter used to get input.For multi-line text input, Text widget is used.If the user
enters a string , which is longer than the available display space of the widget , the
content will be scrolled.This means that the string can not be seen in full.The arrow
key can be used to move to the invisible part of the string.The entry widget is also
limited to a single font.
The general syntax is:
w=Entry(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas.
Some of them are listed below.
1.bg: The normal background color displayed behind the label and the indicator.
2.bd:the size of the border around the indicator.Default is 2 pixels.
3.cursor: pattern of mouse cursor
4.font:The font used for the text.
5.show: Normally the characters that the user types appears in the entry.
To make a password entry that echoes each character as * , set show=“*”.
6.state:The default state is NORMAL.WE van use state=DISABLED to gray out the
control and make it unresponsive.
Eg:
from tkinter import *
root=Tk()
l1=Label(root,text="User Name")
l2=Label(root,text="Password")
E1=Entry(root)
E2=Entry(root)
l1.grid(row=0)
l2.grid(row=1)
E1.grid(row=0,column=1)
E2.grid(row=1,column=1)
root.mainloop()
OUTPUT
8 Height:Height of the button in text lines (for textual buttons) or pixels (for
images).
10 Justify: How to show multiple text lines: LEFT to left-justify each line; CENTER
to center them; or RIGHT to right-justify.
13 State: Set this option to DISABLED to gray out the button and make it
unresponsive. Has the value ACTIVE when the mouse is over it. Default is
NORMAL.
Methods
1 flash()
Causes the button to flash several times between active and normal colors. Leaves
the button in the state it was in originally. Ignored if the button is disabled.
2 invoke()
Calls the button's callback, and returns what that function returns. Has no effect if
the button is disabled or there is no callback.
Eg:
from tkinter import *
top=Tk()
B=Button(top,text="submit")
B.pack()
top.mainloop()
OUTPUT
Message Widget
The Message widget is used to show the message to the user regarding the behavior
of the python application.The message text contains more than one line.Message
Widget is of non-editable type.
Syntax:
w = Message ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Eg:
from tkinter import *
root = Tk()
root.geometry("300x200")
msg = Message( root, text = "Hey!?How are you doing?")
msg.pack()
root.mainloop()
OUTPUT
Text Widget
Text Widget is used where a user wants to insert multiline text fields.This widget
can be used for a variety of applications where the multiline text is required such as
messaging, sending information or displaying information and many other tasks.
Syntax
T = Text(master,option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Options are:
bg – background colour
fg – foreground colour
bd – border of widget.
height – height of the widget.
width – width of the widget.
font – Font type of the text.
cursor – The type of the cursor to be used.
state – defines if the widget will be responsive to mouse or keyboards movements.
yscrollcommand – to make the widget vertically scrollable.
xscrollcommand – to make the widget horizontally scrollable.
Text Widget Methods
Radiobutton Widget
Radiobutton allows the user to choose exactly one option from the set of given
options.It may contain text or image.Also, different methods can also be associated
with radiobutton.
Syntax
W = Radiobutton(master, options)
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Options are same as CheckButton
* value=When a radio button is turned on by the user , its control variable is set to
its current value option.
Methods are same as CheckButton
Eg:
from tkinter import *
root=Tk()
l1=Label(root,text="Gender",)
r1=Radiobutton(root,text="Male",value=1)
r2=Radiobutton(root,text="Female",value=2)
r3=Radiobutton(root,text="Transgender",value=3)
l1.pack(anchor=W)
r1.pack(anchor=W)
r2.pack(anchor=W)
r3.pack(anchor=W)
root.mainloop()
OUTPUT
Listbox Widget
The Listbox widget is used to display a list of items from which a user can select a
number of items.It can only contain text items and all items must have the same font
and color.Depending on how the listbox is configured , the user can select one or
many items from the list.
Syntax
w = Listbox ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
When we first create the listbox, it is empty.We usually insert one or more items to
the list. The insert() method takes an index and a string to insert.Index is an item
number begins from 0.
Option:
bd :This option is used to represent the border width of the widget.
bg :background colour
fg :foreground colour
width :width of the widget.
height :height of the widget.
font :Font type of the text.
cursor :The cursor on the widget which can be an arrow, a dot etc
xscrollcommand : If you want to allow the user to scroll the listbox horizontally,
you can link your listbox widget to a horizontal scrollbar.
yscrollcommand : If you want to allow the user to scroll the listbox vertically,
you can link your listbox widget to a vertical scrollbar.
selectmode :Determines how many items can be selected, and how mouse
drags affects the selection.
* BROWSE: Default value.You can only select one item from the listbox.
If you click on an item and then drag to a different line , the
selection will follow the mouse.
*SINGLE: You can only select one item, and you can’t drag the mouse.
*MULTIPLE: You can select any number of items at once.
*EXTENDED: You can select any adjacent group of lines at once by clicking
on the first line and dragging to the last line.
Eg2:
from tkinter import *
root=Tk()
list=Listbox(root,height = 10,width = 15,bg = "grey",fg = "yellow")
root.geometry("300x250")
label=Label(root,text=" FOOD ITEMS")
list.insert(1, "Nachos")
list.insert(2, "Sandwich")
list.insert(3, "Burger")
list.insert(4, "Pizza")
list.insert(5, "Burrito")
label.pack()
list.pack()
root.mainloop()
OUTPUT
Scrollbar Widget
The scrollbar widget is used to implement vertical scrolled widgets that is scroll
down the content.
We can also create the horizontal scrollbars to the Entry widget.
Syntax
w = Scrollbar ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget
Options are:
activebackground :The color of the slider and arrowheads when the mouse is over
them.
bd: This option is used to represent the border width of the widget.
bg: The color of the slider and arrowheads when the mouse is not over them.
cursor: In this option, the mouse pointer is changed to the cursor type,set to this
option which can be an arrow, dot, etc
width: Width of the scrollbar (its y dimension if horizontal, and its x dimension if
vertical).Default is 16.
orient: This option can be set to HORIZONTAL or VERTICAL depending upon the
orientation of the scrollbar.
jump: This option is used to control the behavior of the scroll jump. If it set to 1,
then the callback is called when the user releases the mouse button.
Methods used in this widgets are as follows:
1.get():This method is used to returns the two numbers a and b
which represents the current position of the scrollbar.
2.set ( first, last ) :To connect a scrollbar to another widget w, set w’s
xscrollcommand or yscrollcommand to the scrollbar’s set() method.
The arguments have the same meaning as the values returned by the
get() method.
Eg:
from tkinter import *
root = Tk()
root.geometry("300x250")
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )
mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert(END, "This is line number " + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()
OUTPUT
Spinbox widget
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
Syntax
w = Spinbox ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Eg:
from Tkinter import *
master = Tk()
w = Spinbox(master, from_=0, to=10)
w.pack()
mainloop()
OUTPUT
Menu widget
Menus are the important part of any GUI.It allows us to create all kinds of menus
that can be used by our applications.
Syntax
w = Menu ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Eg:
from tkinter import *
root = Tk()
root.title('Menu Demonstration')
# Creating Menubar
menubar = Menu(root)
# Adding File Menu and commands
file = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='File', menu = file)
file.add_command(label ='New File', command = None)
file.add_command(label ='Open...', command = None)
file.add_command(label ='Save', command = None)
# Adding Edit Menu and commands
edit = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Edit', menu = edit)
edit.add_command(label ='Cut', command = None)
edit.add_command(label ='Copy', command = None)
edit.add_command(label ='Paste', command = None)
edit.add_separator()
edit.add_command(label ='Find...', command = None)
edit.add_command(label ='Find again', command = None)
# display Menu
root.config(menu = menubar)
mainloop()
OUTPUT
Menubutton widget
A Menubutton is a part of a drop-down menu that stays on the screen all the time.
Every Menubutton is associates with a Menu widget that can display the choices for
that menu button when user clicks on it.
Syntax:
m=Menubutton(master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Options are:
1.activebackground: The back ground color when the mouse is over the menu button.
2.activeforeground: The foreground color when the mouse is over the menu button.
3.anchor : same as other widget
4.bg : Normal background color behind the label and indicator.
5.bd : size of border.
6.cursor : same as other widget.
7.relief : Selects three- dimensional border shading effects.
8.state : Set state=DISABLED , to gray out the menu button and make it
unresponsive.
Eg:
from tkinter import *
root = Tk()
root.geometry("300x200")
l = Label(root, text ='CONCORD', font = "50")
l.pack()
menubutton = Menubutton(root, text = "Menu")
menubutton.menu = Menu(menubutton)
menubutton["menu"]= menubutton.menu
menubutton.menu.add_checkbutton(label = "Courses")
menubutton.menu.add_checkbutton(label = "Students")
menubutton.menu.add_checkbutton(label = "Careers")
menubutton.pack()
root.mainloop()
OUTPUT
4 Command It is set to the procedure which is called each time when we move
the slider. If the slider is moved rapidly, the callback is done
when it settles.
5 Cursor The mouse pointer is changed to the cursor type assigned to this
option. It can be an arrow, dot, etc.
6 Digits If the control variable used to control the scale data is of string
type, this option is used to specify the number of digits when the
numeric scale is converted to a string.
7 Tickinterval The scale values are displayed on the multiple of the specified
tick interval. The default value of the tickinterval is 0.
10 Label This can be set to some text which can be shown as a label with
the scale. It is shown in the top left corner if the scale is
horizontal or the top right corner if the scale is vertical.
Methods
SN Method Description
Eg:
from tkinter import *
top=Tk()
top.geometry("200x200")
s=Scale(top,from_=0,to=20,tickinterval=4)
s.set(10)
s.pack()
top.mainloop()
OUTPUT
Frames
The Frame widget is for grouping and organizing other widgets.It works like
a container , which is responsible for arranging the position of other widgets.It uses
a rectangular area on the screen to organize the layout and to provide padding of
these widgets.A Frame can also be used as a foundation class to implement complex
widgets.If you make a GUI app, you’ll be using different widgets, Those widgets
need to be organized somehow, that’s where a frame comes in.
Syntax:
f=Frame(master,options)
Options:
bg: Background color
bd:Size of border around it.
cursor:Style of mouse cursor.
height:Vertical dimension of the new frame.
width:Horizontal dimension of the new frame.
Eg:
from tkinter import *
root=Tk()
root.geometry("200x200")
frame=Frame(root)
frame.pack()
bottomframe=Frame(root)
bottomframe.pack(side=BOTTOM)
redbutton=Button(frame,text="APPLE",fg="red")
redbutton.pack(side=LEFT)
greenbutton=Button(frame,text="PEAR",fg="green")
greenbutton.pack(side=LEFT)
bluebutton=Button(frame,text="GRAPES",fg="blue")
bluebutton.pack(side=LEFT)
blackbutton=Button(bottomframe,text="BLACKBERRY",fg="black")
blackbutton.pack(side=BOTTOM)
root.mainloop()
OUTPUT
Canvas Widget
The Canvas widget supplies graphics facilities for tkinter.Among these graphical
objects are lines, circles , images etc.With this widget it is possible to draw graphs
and plots.
Syntax:
c=Canvas(master,option)
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Optional parameters:
• root = root window.
• height = height of the canvas widget.
• width = width of the canvas widget.
• bg = background colour for canvas.
• bd = border of the canvas window.
• scrollregion (w, n, e, s)tuple defined as a region for scrolling left, top, bottom
and right.
• highlightcolor colour shown in the focus highlight.
• cursor It can be defined as a cursor for the canvas which can be a circle, a do,
an arrow etc.
• confine decides if canvas can be accessed outside the scroll region.
• relief type of the border which can be SUNKEN, RAISED, GROOVE and
RIDGE.
Eg:
import tkinter as tk
root = tk.Tk()
w = tk.Label(root, text="Red Sun", bg="red", fg="white")
w.pack(fill=tk.X, padx=10)
w = tk.Label(root, text="Green Grass", bg="green",fg="black")
w.pack(fill=tk.X, padx=10)
w = tk.Label(root, text="Blue Sky", bg="blue",fg="white")
w.pack(fill=tk.X, padx=10)
tk.mainloop()
OUTPUT
2.Grid Layout
The Grid geometry manager places the widget in a 2 – dimensional table,
which consist of a number of rows and columns.The position of a widget is defined
by a row and column numbers.Using the grid manager means that you create a
widget , and use the grid method to tell the manager in which row and column to
place them.The size of the grid does not have to be defined, because the manager
automatically determines the best dimensions for the widgets used.
Syntax:
widget.grid(row,column, other options)
Options:
1.row : The row to put the widget in.Default is the first row that is still empty.
2.column: The column to put widget in.Default 0 (leftmost column)
3.padx,pady : Shows how many pixels to pad widget, horizontally and vertically.
Eg:
from tkinter import *
root = Tk()
root.geometry("300x200")
l1=Label(root,text="RED",width=15)
l2=Label(root,text="GREEN",width=15)
l3=Label(root,text="BLUE",width=15)
b1=Button(root,bg="red",width=15)
b2=Button(root,bg="green",width=15)
b3=Button(root,bg="blue",width=15)
l1.grid(row=0,column=0)
b1.grid(row=0,column=1)
l2.grid(row=1,column=0)
b2.grid(row=1,column=1)
l3.grid(row=2,column=0)
b3.grid(row=2,column=1)
root.mainloop()
OUTPUT
3.Place Layout
The geometry manager allows us to explicitly set the position and size of a
window, either in absolute terms, or relative to another window.Place manager can
be accessed through the place method.It can be applied to all standard widgets.
Syntax:
widget.place(options)
Options:
1.anchor: The exact spot of widget other options refers to : may be
N,E,S,W,NE,NW,SE,SW. compass directions indicating the corners and sides of
widget: Default is NW ( the upper left corner of widget ).
2.bordermode: INSIDE ( the default ) to indicate that other options refers to the
parent’s inside ( ignoring the parent’s border) : OUTSIDE otherwise.
3.height,width : Height and Width in pixels.
4.x,y : Horizontal and Vertical offset in pixels.
Eg:
from tkinter import *
top=Tk()
top.geometry("300x300")
B1=Button(top,text="SUBMIT",bg="red")
B2=Button(top,text="CANCEL",bg="red")
B1.place(bordermode=OUTSIDE,height=100,width=100,x=10,y=50)
B2.place(bordermode=OUTSIDE,height=100,width=100,x=120,y=50)
top.mainloop()
OUTPUT