0% found this document useful (0 votes)
11 views115 pages

Unit Iii: Graphical User Interface

gui

Uploaded by

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

Unit Iii: Graphical User Interface

gui

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 115

UNIT III

GRAPHICAL USER INTERFACE


• A person who interacts with a software or application is called a 'user‟.
• There are two ways for user to interact with any application.
• Character User Interface
• Graphical User Interface
• The first way is where the user gives some commands to perform the work.
• For example, if he wants to print files contents, he can type PRINT command.
Here the user should know the syntax and correct usage of PRINT Command.
Only then he can interact with the application.
• This application of environment where the user uses commands or characters
to interact with the application is called CUI (Character User Interface).
• One example for CUI is MS-DOS operating system.
• The disadvantage of CUI is that the user has to remember several commands
and their usage with correct syntax.
• A person who does not know anything in a computers will find CUl very
difficult.
• The second way to interact with an application is through graphics, pictures or
images. Here the user need not remember any commands.
• He can perform the task just by clicking on relevant images.
• For example, to send data to printer, the user will simply click on the Printer
image (or picture).
• Then he has to tell how many copies he wants and the printing will continue.
• This environment where the user can interact with an application through
graphics or images is called GUI (Graphical User Interface).
• One example for GUI is Windows operating system
• GUI offers the following advantages:
• It is user-friendly. The user need not worry about any commands. Even a
layman will be able to work with the application developed using GUI.
• It adds attraction and beauty to any application by adding pictures, colors,
menus, animation, etc. For example, all websites on Internet are developed
using GUI.
• It is possible to simulate the real life objects using GUI. For example, a
calculator program may actually display a real calculator on the screen. The
user feels that he is interacting with a real calculator and he would be able to
use it without any difficulty or special training. So, GUI eliminates the need of
user training.
• GUI helps to create graphical component like push buttons, radio buttons,
check buttons, menus, etc, and use them effectively.
• GUI in Python Python offers tkinter module to create graphical programs.
• The tkinter represents 'toolkit’ interface for GUI.
• This is an interface for Python programmers that enable them to use the
classes of TK module of TCL/TK language.
• The TCL (Tool Command Language) is a powerful dynamic programming
language, suitable for web and desktop applications, networking,
administration, testing and many more.
• It is open source and hence can be used by any one freely.
• TCL language uses TK (Tool Kit) language to generate graphics.
• TK provides standard GUI not only for TCL but also for many other dynamic
programming languages like Python.
• Hence, this TK is used by Python programmers in developing GUI applications
through Python's tkinter module.
• The following are the general steps involved in basic GUI programs:
• Create the root window. The root window is the top level window that
provides rectangular space on the screen where we can display text, colors,
images, components, etc.
• In the root window, we have to allocate space for our use. This is done by
creating a Canvas or Frame. Canvas and frame are child windows in the root
window.
• We use canvas for displaying drawings like lines, arcs, circles, shapes, etc.
• We use frame for the purpose of displaying components like push buttons,
check buttons, menus, etc. These components are also called widgets.
• When the user clicks on a widget like push button, we have to handle that
event. It means we have to respond to the events by performing the desired
tasks.
• Steps to create a basic GUI program
• There are five main steps that are required to get your GUI up and running:

1. Import the tkinter module (or from tkinter import *).


2. Create a top-level windowing object that contains your entire GUI
application.
3. Build all your GUI components (and functionality) on top (or within) of your
top-level windowing object.
4. Connect these GUI components to the underlying application code.
5. Enter the main event loop.
• The Root Window
• To display the graphical output, we need space on the screen.
• This space that is initially allocated to every GUIprogram is called top level
window or root window.
• We can say that the root window is the highest level GUI component in any
tkinter application.
• We can reach this root window by creating an object to Tk class.
• The root window will have a title bar that contains minimize, resize and close
options.
• When you click on close X option, the window will be destroyed.
• Program : A Python program to create root window or top level window
• # Import allcomponent from tkinter
• from tkinter import *

• # create root window


• root = Tk()

• # all widgets will be here


• # wait and watch for any events that may take place in the root window
• root.mainloop()
• We can display our own title in the root window's title bar.
• We can also set the size of the window to something like 400 pixels X 300
pixels.
• It is also possible to replace the TKs leaf image with an icon of our choice.
• For this, we need to use the ico file that contains an image.
• A Python program to create root window with some options.
• Fonts and Colors
• A font represents a type of displaying letters and numbers.
• In tkinter, fonts are mentioned using a tuple that contains font family name,
size and font style as:
fnt =('Times', -40, 'bold italic underline overstrike')
• Here, the font family name is “Times‟ and font size is 40 pixels.
• If the size is a positive number, it indicates size in points. If the size is a
negative number, it indicates size in pixels.
• The style of the font can be 'bold', italic', 'underline', 'overstrike‟.
• We can mention any one or more styles as a string.
• The following program is useful to know the available font families in your
system.
• All fonts are available in tkinter.font module inside tkinter module.
• Colors in tkinter can be displayed directly by mentioning their names as: blue,
lightblue,darkblue, red, lightred, darkred, black, white, yellow, magenta, cyan,
etc.
• We can also Specify colors using the hexadecimal numbers in the format: 8
bits per color or12 bits per color For example, #000000 represents black and
#ff0000 represents red.
Program: A Python program to know the available font families.
• Working with Containers
• A container is a component that is used as a place where drawings or widgets
can be displayed.
• In short, a container is a space that displays the output to the user.
• There are two important containers:
• Canvas: This is a container that is generally used to draw shapes like lines,
curves, arcs and circles.
• Frame: This is a container that is generally used to display widgets like
buttons, check buttons or menus.
• After creating the root window, we have to create space, i.e. the container in
the root window so that we can use this space for displaying any drawings or
widgets.
• Canvas
• A canvas is a rectangular area which can be used for drawing pictures like
lines, circles, polygons, arcs, etc.
• To create a canvas, we should create an object to Canvas class as:
c = Canvas (root, bg="blue", height=500, width=600, cursor='pencil')
• Here, c is the Canvas class object, root is the name of the parent window bg
represents background color, height and width represent the height and
width of the canvas in pixels.
• A pixel (picture element) is a minute dot with which all the text and pictures
on the monitor are composed.
• When the monitor screen resolution is 1360X768, it indicates that the screen
can accommodate 1360 pixels width-wise and 768 pixels height-wise
• The top left corner of the screen will be at (0, 0) pixels as x and y coordinates.
• When we move from left to right, the x coordinate increases and when we
move from top to bottom, the y coordinate increases.
• The top right corner will be at (1360, 0). The bottom left corner will be at (0,
768) and the bottom right corner will be at (1360, 768).
• The option 'cursor' represents the shape of the cursor in the canvas.
Important cursor shapes are: arrow, box_spiral, center_ptr, circle, clock,
coffee_mug, cross, cross_reverse,crosshair, diamond_cross, dot,
double_arrow, exchange, handl, hand2, heart, left_ptr, mouse, pencil, plus,
question_arrow, right_ptr, star, tcross, top side, umbrella, watch, xterm,
X_cursor.
• Colors in the canvas can be displayed directly by mentioning their names as:
blue, lightblue, darkblue, red, lightred, darkred, black, white, yellow, magenta,
cyan, etc.
• we can also specity colors using hexadecimal numbers in the format: 8 bits
per color or 12 bits per color For example,#000000 represents black and
#ffO000 represents red.
• Once the canvas is created, it should be added to the root window.
• Then only it will be visible.
• This is done using the pack() method, as follows:
c.pack()
• After the canvas is created, we can draw any shapes on the canvas.
• Create line, we can use create_line() mnethod, as
line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn, width=n,
fill=“color")
id= c.create_line(50,50,200, 50, 200, 150, width=4, fill="white")
• This creates a line with the connecting points(50,50), (200, 50) and (200,
150). 'width' specifies the width of the line.
• The default width is 1 pixel. fill specifies the color of the line.
• The create line0 method returns an identification number.
• create an oval, we can use the create_oval() method.
• An oval is also called ellipse.
oval = canvas.create_oval(x0, y0, x1, y1, width=n, fill=“color",
outline=“color", activefill=“color")
id =c..create.oval (l00, 100,400, 300, width=5, fill="yellow", outline=”red”,
activefill="green”)
• This creates an oval in the rectangular area defined by the top left
coordinates(100,100) and bottom lower coordinates (400, 300).
• If the rectangle has same width and height, Then the oval will become a circle.
• width' represents the width of the Oval in pixels.
• fill represents the color to fill and 'outline' represents the color to be used for
the border.
• The option 'activefill' represents the color to be filled when the mouse is
placed on the oval.
• Create a polygon, we can use the create.polygon() method.
• A polygon represents several points connected by either straight lines or
smooth lines.
poly= canvas.create_polygon(x0, y0, x1, y1,...xn, yn, width=n, fill=“color",
outline=“color", smooth=1, activefill=“color")
id =c.create_ polygon(10, 10, 200, 200,300, 200, width=3, fill="green",
outline=”red”, smooth=1,activefill=" lightblue”)
• Here, the polygon is created using the points (10, 10), (200, 200), (300, 200)
and then the last point is again connected to the first point, i.e. (10, 10).
• The option 'smooth' can become 0 or 1 If 0, it indicates a polygon with sharp
edges and 1 indicates a polygon with smooth edges.
• Create a rectangle or square shaped box, use the create_rectangle() method :
Rect = canvas. create_rectangle(x0, y0, x1, y1, width=n, fill=“color",
outline=“color",activefill=“color”)
id=c.create_rectangle(500, 200,700, 600, width= 2, fill="gray",
outline="black", activefill="yellow'")
• Here, the rectangle will be formed with the top left coordinate at (500, 200)
pixels and the lower bottom coordinate at (700, 600).
• The color of the rectangle will change from gray to yellow when the mouse is
placed on the rectangle.
• create_text() method to display some text in the canvas.
• Txt = Canvas.create_text(500, 100, text="My canvas", font= fnt, fill=“color",
activefill=“color")
id=create_ text (500, 100, text="My canvas", font= fnt, fill="yellow",
activefill="green”)
• Here, the 'font' option is showing fnt object that can be created as:
fnt=(‘Times’, 40, 'bold')
fnt =(‘Times’, -40, ‘bold italic underline')
• The first option ‘Times' represents the font family name.
• This can be Times, Helvetica, Courier, etc.
• The second option represents a number (40) that indicates the size of the font
in points.
• If we want to mention the size of the font in pixels, we should use minus sign
before the size (-40).
• The third option indicates the style of the font.
• There are 3 styles: bold, italic and underline. We can mention any one or all
the styles.
• If do not want any style, we need not mention this option.
• Program: A GUI program that demonstrates the creation of various shapes
in canvas.
• from tkinter import*
• # create, root window
• root = Tk()
• #Create Canvas as a child to root window
• c=Canvas (root, bg="blue", height=700, width=1200, cursor='pencil')
• # create a line in the canvas
• id = c.create_line (50, 50, 200, 50, 200, 150, width=4, fill="white")
• # create an oval in the canvas
• id =c.create_oval (100, 100, 400, 300, width=5, fill="yellow" , outline= "red",
activefill="green")
• #create a polygon in the canvas
• id =c.create_polygon (10, 10, 200, 200, 300, 200, width= 3, fill="green" ,
outline= "red", smooth=1,activefill="light blue")
• #create a rectangle in the canvas id = c.create_rectangle (500, 200, 700, 600,
width =2, fill="gray", outline ="black", activefill ="yellow")
• #create some text in the canvas
• fnt =('Times', 40, "bold italic underline")
• id = c.create_text(500, 100, text= "My canvas", font=fnt, fill="yellow",
activefill= "green")
• # add canvas to the root window
• c.pack()
• # wait for any events
• root.mainloop()
• Creating Arcs
• An arc represents a part of an ellipse or circle.
• Arcs can be created using the create_arc() method as:
arc = canvas.create_arc(x0, y0, x1, y1, start=0, extent=150, fill=“color",
outline=“color", style=”arcpattern”)
id = c.create_arc(100, 100, 400, 300, width=3, start=270, extent=180,
outline="red", style=”arc")
• Here, the arc is created in the rectangular space defined by the coordinates
(100, 100) and (400, 300).
• The width of the arc will be 3 pixels.
• The arc will start at an angle 270 degrees and extend for another 180 degrees
(i.e. up to 450 degrees means 450 - 360 = 90 degrees).
• The outline of the arc will be in red color. 'style' option can be "arc" for
drawing arcs. “style” can be "pie slice” and “chord".
• Program : A Python program to create arcs in different shapes
• from tkinter import*
• #create root window
• root = TK()
• #create Canvas as a child to root Window
• c= canvas(root, bg="white", height =700, width= 1200)
• # create arcs in the canvas
• id = c.create_ arc(100, 100, 400, 300, width=3, start= 270, Extent=120,
outline="red", style= “arc)
• id = c.create_ arc(500, 100, 800, 300, width=3, start=90, entent=120,outline=
"red", style ="arc")
• id = c.create_ arc(100, 400, 400, 600, width=3, start=0, extent=120, outline=
"blue", style ="arc")
• id = c.create_ arc(500, 400, 800, 600, width=3, start=180,extent=120,outline
="blue", style =”arc”)
• id = c.create_ arc (900, 400, 1200, 600, width=3, start=90, extent=90, outline
="black", style="arc")
• # add canvas to the root
• c.pack()
• # wait for any events
• root.mainloop()
• Display image
• Image - Creates an image item, which can be an instance of either the
BitmapImage or the PhotoImage classes.
• We can display an image in the canvas with the help of create_image() method.
• We should first load the image into a file using PhotoImage class as:
• file1= PhotoImage( file= rose.gif) # Load rose.gif into file
• Now, the image is available in 'file'. This image can be displayed in the canvas using
create_image() method as:
id= c.create_ image (500, 200, anchor =NE, image = file1, activeimage=file2)
• Here, the image is displayed relative to the point represented by the coordinates
(500, 200).
• The image can be placed in any direction from this point indicated by 'anchor’
option.
• The directions are represented by actual 8 directions on the earth: NW, N, NE,
E,SE, S, SW, W and CENTER.
• ‘image’ represents the image file name that should be displayed in the canvas.
• 'activeimage' represents the image file name that should be displayed when the
mouse is placed on the image.
• Directions that can be used in Anchor Option
• Frame
• A frame is similar to canvas that represents a rectangular area where some
text or widgets can be displayed.
• Our root window is in fact a frame.
• To create a frame, we can create an object of Frame class as:
frame= Frame (root, height=n, width=m, bg="color", cursor="cursortype")
f= Frame (root, height=400, width=500, bg="yellow", cursor="cross")
• Here, f is the object of Frame class.
• The frame is created as a child of ‘root' window.
• The options 'height' and ‘width' represent the height and width of the frame
in pixels.
• bg represents the back ground color to be displayed and 'cursor' indicates the
type of the cursor to he be displayed in the frame.
• Once the frame is created, it should be added to the root window using the
pack() method as follows
f.pack()
• Program : A GUI program to display a frame in the root window
• from tkinter import *
• # create root window
• root = Tk()
• #give a title for root window
• root.title(“My Frame")
• # create a frame as child to root window
• f= Frame (root, height=400, width=500, bg="yellow", cursor=”cross”)
• #attach the frame to root window
• f.pack()
• #let the root window wait for any events
• root.mainloop( )
• Widgets
• A widget is a GUI component that is displayed on the screen and can perform
a task as desired by the user.
• We create widgets as objects.
• For example, a push button is a widget that is nothing but an object of Button
class.
• Similarly, label is a widget that is an object of Label class.
• Once a widget is created, it should be added to canvas or frame.
• The following are important widgets in Python:
• Button
• Label
• Message
• Text
• Scrollbar
• Checkbutton
• Radiobutton
• Entry
• Spinbox
• Listbox
• Menu
• In general, working with widgets takes the following four steps:
1. Create the widgets that are needed in the program. A 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 Button class object.
• As an example, suppose we want to create a push button, we can create an
object to Button class as:
b = Button(f, text='My Button')
• Here, f is Frame object to which the button is added. ‘My Button' is the text
that is displayed on the button.
2. When the user interacts with a widget, he will generate an event.
• For example, clicking on a push button is an event. Such events should be
handled by writing functions or routines. These functions are called in
response to the events. Hence they are called 'callback handlers' or 'event
handlers'. Other examples for events are pressing the Enter button, right
clicking the mouse button, etc.
• As an example, let's write a function that may be called in response to button
click
def buttonClick(self):
print('You have clicked me')
3. When the user clicks on the push button, that “clicking‟ event should be
linked with the 'callback handler' function. Then only the button widget will
appear as if it is performing some task.
• As an example, let's bind the button click with the function as:
b.bind('<Button-1>', buttonclick)
• Here, ‘b' represents the push button. <Button-1> indicates the left mouse
button.
• When the user presses the left mouse button, the ‘buttonClick' function is
called as these are linked by bind method in the preceding code.
4. The preceding 3 steps make the widgets ready for the user. Now, the user
has to interact with the widgets. This is done by entering text from the
keyboard or pressing mouse button. These are called events. These events
are continuously monitored by our program with the help of a loop, called
event loop
• As an example, we can use the mainloop() method that waits and processes.
root.mainloop()
• Here,‟ root‟ is the object of root window in Python GUI The events in root
window are continuously observed by the mainloop method. It means clicking
the mouse or pressing a button on the keyboard are accepted by mainloop()
and then the mainloop() calls the corresponding even handler function
• Button Widget
• A push button is a component that performs some action when clicked.
• These buttons are created as objects of Button class as:
b = Button(f, text='display text', width=n, height=m, bg='color', fg='color',
activebackground='color', activeforeground='color')
b = Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue',
activebackground='green', activeforeground='red')
• Here, “b‟ is the object of Button class.
• ‟ f” represents the frame for which the button is created as a child. It means the
button is shown in the frame.
• The 'text' option represents the text to be displayed on the button.
• “width‟ represents the width of the button in characters. If an image is displayed
on the button instead of text, then width represents the width in pixels.
• 'height' represents the height of the button in textual lines. If an image is
displayed on the button, then 'height' represents the height of the button in pixels.
• bg represents the back ground color and 'fg' represents foreground the color of
the button.
• 'activebackground' represents the background color when the button is clicked.
• 'activeforeground' represents the foreground color when the button is clicked.
• We can also display an image on the button as:
• # first load the image into file1
filel1 =PhotoImage(file="rose.jpg")
• # create a push button with image
b = Button(f, image=file1, width=150, height=100, bg='yellow',fg='blue',
ativebackground='green', activeforeground='red')
• In the preceding statement, observe that the width and height of the button
are mentioned in pixels
• We create a frame first and then create a push button with some options and
add the button to the frame.
• Then we link the mouse left button with the buttonChick method using bind
method as:
b.bind('<Button 1>’, buttonClick)
• Here, <Button-1> represents the mouse left button that is linked with
buttonClick() method.
• It means when the mouse left button is clicked, the buttonClick() method is
called. This method is called event handler.
• In the place of <Button-1>, we can also use <Button-2>.
• In this case, mouse middle button is linked with the event handler method.
• The middle button is not found in most of the mousses now-a-days.
<Button-3> represents the mouse right button.
• Similarly, <Enter> represents that the event handler method should be
executed when the mouse pointer is placed on the push button.
• In the preceding program, we want to make 2 modifications.
• First, we will eliminate bind method and we will use command option to link
the push button with event handler function as:
D = Button (f, text='My Button', width=15, height=2, bg=”yellow” , fg='blue',
activebackground='green', activeforeground='red', command=buttonClick)
• When we create 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= “Red”, width=15, height=2, command=lambda:
buttonClick(1))
• Here, we are creating a push button “b1‟.
• Please observe the “command” option. Here, we are using the lambda
expression to pass the argument 1 to the buttonClick() method, in the
following format:
• command=1ambda: buttonClick(arg1, arg2,….)
• Usualy, “command” option allows us to mention the method name only and it
is not possible to pass arguments to the method.
• Suppose we want to pass arguments, then need to use lambda expression as
shown in the previous statement.
• In Program below, we are creating 3 push buttons by the names “Red‟,
“Green” and “Blue‟.
• When the user clicks a button we will change the back ground color of the
frame according to the button clicked.
• This is possible by passing an integer 1, 2 or 3 to the event handler method to
indicate which button is clicked.
• This integer is stored in a variable 'num' at the method.
• When the button is clicked, we are changing the background color of the
frame as:
• def buttonClick(self, num) :
if num==1:
self. f["bg"]= 'red'
if num==2
self.f["bg"]= ‘green'
• Here, observe that the bg' is the option of the frame “f‟.
• To set the back ground color of the frame, we can write:
• self.f["bg"]= 'red' # set new color for bg
• In the same way, we can set other options for the frame as:
• self.f[“height”]= 500 # set new height
• self.f[“ width”] =600 # set new width
• You can follow the same procedure to set new values for the options of any
widget.
• A Python program to create three push buttons and change the background
of the frame according to the button clicked by the user.
• from tkinter import*
• class MyButton:
• #constructor
• def _init__(self, root):
• #create a frame as child to root window
• self. f = Frame (root, height=400, width=500)
• # let the frame will not shrink
• self.f.propagate(0)
• # attach the frame to root window
• self.f.pack()
• # create 3 push buttons and bind them to buttonclick method and pass a
number
• self.bl = Button(self.f, text=‟red‟, width=15, height=2,command=lambda:
self.buttonClick(1))
• self.b2 = Button(self.f, text=‟Green‟, width=15, height=2,command=lambda:
self.buttonClick(2))
• self.b3 = Button(self.f, text=‟Blue‟, width=15, height=2, command=lambda:
self.buttonClick(3))
• # attach buttons to the frame
• self.b1.pack()
• self.b2.pack()
• self.b3.pack()
• # method to be called when the button is clicked
• def buttonClick(self, num):
• #set the background color of frame depending on the button clicked
if num=1:
self.f[“bg”]= “red‟'
if num==2:
self.f[“bg”]= “green‟'
if num==3
self.f[“bg”]= “blue‟
• # create root window
• root = Tk()
• # create an object to MyButton class
• mb = MyButton(root)
• # the root window handles the mouse click event
• root.mainloop()
• Arranging Widgets in the Frame
• Once we create widgets or components, we can arrange them in the frame in
a particular manner. Arranging the widgets in the frame is called layout
management.
• There are three types of layout managers
– Pack layout manager
– Grid Layout manager
– Place layout manager
• Pack layout manager
• Pack layout manager uses pack() method. This method is useful to associate a
widget with its parent component.
• While using the pack() method, we can mention the position of the widget
using “fill‟ or “side‟ options
b.pack(fill=X)
b.pack(fill=Y)
• The “fill‟ option can take the values: X, Y, BOTH, NONE.
• The value X represents that the widget should occupy the frame horizontally.
• The value Y represents that the widget should hold occupy vertically.
• BOTH represents that the widget should occupy in both the directions.
• NONE represents that the widget should be displayed as it is.
• The default value is NONE.
• Along with “fill‟ option, we can use padx and pady options that represent
how much space should be left around the component horizontally and
vertically.
• For example:
• #occupy vertically, space on x-axis 10 px, on Y-axis 15 px
• b1.pack(fill=Y, padx=10, pady=15)
• # occupy horizontally. Space on x-axis 10 px, on Y-axis 15 px
• b2.pack(fill=X, padx=10, pady=15)
• b3.pack(fill=Y,padx=10,pady=15) # occupy vertically, space on x-axis 10 px, on
Y-axis 15 px
• b4.pack(fill=X) # occupy horizontally, No space outside the widget
• The output in this case
• The pack() method can take another option “side‟ which is used to place the
widgets side by side.
• “side‟ can take the values LEFT, RIGHT, TOP or BOTTOM.
• The default value is TOP.
• For example,
• # align towards left with 10 px and 15 px spaces
• b1.pack(side=LEFT, padx=10, pady=15)
• # align towards bottom with 10 px and 15 px spaces
• b2.pack(side=BOTTOM, padx=10, pady=15)
• # align towards right with 0 px space around the widget
• b3.pack(side=RIGHT)
• # align towards top with 0 px space around the widget
• b4.pack()
• Output : Arrangement of buttons using pack() method with 'side' option
• Grid layout manager
• Grid layout manager uses the grid() method to arrange the widgets in a two
dimensional table that contains rows and columns.
• The horizontal arrangement of data is called “row‟ and vertical arrangement
is called “column‟.
• The position of a widget is defined by a row and a column number.
• The size of the table is determined by the grid layout manager depending on
the widgets size.
• # display in 0th row, 0th column with spaces around
• b1.grid(row=0, column=0, padx=10, pady=15)
• # display in 0th row, 1st column with spaces around
• b2.grid(row=0, column=1, padx=10, pady=15)
• # display in 0th row, 2nd column without spaces around
• b3.grid(row=0, column=2)
• # display in 1st row, 3rd column without spaces around
• b4.grid(row=1, column=3)
• Output:
• Place layout manager
• Place layout manager uses the place() method to arrange the widgets.
• The place() method takes x and y coordinates of the widget along with width
and height of the window where the widget has to be displayed.
• For example:
• # display at (20, 30) coordinates in the window 100 px width and 50 px height
• b1.place(x=20, y=30, width=100, height=50)
• b2.place(x=20, y=100, width=100, height=50) # display at (20, 100)
• b3.place(x=200, y=100, width=100,height=50)# display at (200, 100)
• b4.place(x=200, y=200, width=100, height=50) # display at (200, 100)

• 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))

• Observe the on_select() method. It has a parameter “event‟ that is useful to


catch the ListboxSelect event. We need not do anything with this event inside
the method.
• To retrieve the indexes or position numbers of the selected items, we can use
curselection() method of Listbox class.
• Suppose, we want to know the names of the items based on the indexes, we
can use get() method of the Listbox class.
• In the on_select() method, we are appending the names of the selected items
to a list box. Later the contents of this list box can be displayed in a Text box.
• Program: A Python program to create a list box with Universities names and
display the selected Universities names in a text box.
from tkinter import *
class ListboxDemo:
def __init__(self, root):
self.f = Frame(root,width=700, height=400)
# let the frame will not shrink
self.f.propagate(0)
# attach the frame to root window
self.f.pack()
# create a label
self.lbl = Label(self.f, text="Click one or more of the Universities
below:", font="Calibri 14")
self.lbl.place(x=50, y=50)
# create list box with universities names
self.lb = Listbox(self.f, font="Arial 12 bold", fg='blue',bg='yellow',
height=8, selectmode=MULTIPLE)
self.lb.place(x=50, y=100)
# using for loop, insert items into list box
for i in ["Mangalore University", "Bangalore University", "Mysore
University", "Kuvempu University", "Darwad University","Central University"]:
self.lb.insert (END, i)
# bind the listboxselect event to on_select() method
self.lb.bind('<<ListboxSelect>>', self.on_select)
# create text box to display selected items
self.t = Text(self.f, width=40, height=6, wrap=WORD)
self.t.place(x=300, y=100)
def on_select(self, event):
# create an empty list box
self.lst= []
# know the indexes of the selected items
indexes = self.lb.curselection()
# retrieve the items names depending on indexes
# append the items names to the list box
for i in indexes:
self.lst.append(self.lb.get(i))
#delete the previous content of the text box
self.t.delete(0.0, END)
#insert the new contents into the text box
self.t.insert(0.0, self.lst)

# create root window


root = Tk()

#title for the root window


root.title("List box demonstration.")

#create object to our class


obj = ListboxDemo(root)

#handle any events


root.mainloop()
• Menu Widget
• First, create a root window and set its title to 'Menu Demo':
root = Tk()
root.title('Menu Demo')
• Second, create a menu bar and assign it to the menu option of the root window:
menubar = Menu(root)
root.config(menu=menubar)
• Note that each top-level window can only have only one menu bar.
• Third, create a File menu whose container is the menubar:
file_menu = Menu(menubar)
• Fourth, add a menu item to the file_menu:
file_menu.add_command( label='Exit', command=root.destroy)
• In this example, the label of the menu item is Exit.
• When you click the Exit menu item, Python will call the root.destroy() method
automatically to close the root window.
• Finally, add the File menu to the menubar:
menubar.add_cascade( label="File", menu=file_menu, underline=0 )
• The underline option allows you to create a keyboard shortcut.
• It specifies the character position that should be underlined.
• Note that the position starts from zero. In this example, we specify it as the first
character which is F. And you can select it by using the Alt+F keyboard shortcut.
• Put it all together:
from tkinter import *
# root window
root = Tk()
root.title('Menu Demo')
# create a menubar
menubar = Menu(root)
root.config(menu=menubar)
# create a menu
file_menu = Menu(menubar)
# add a menu item to the menu
file_menu.add_command( label='Exit', command=root.destroy )
# add the File menu to the menubar
menubar.add_cascade( label="File", menu=file_menu )
root.mainloop()
• By default, Tkinter adds a dashed line before the first menu item.
• When you click the dashed line, the main window will detach the menu from it
like this:
• To remove the dashed line, you can set the tearoff property of the menu
to False:
• file_menu = Menu(menubar, tearoff=False)
• # add a submenu
sub_menu = Menu(file_menu, tearoff=0)
sub_menu.add_command(label='Keyboard Shortcuts')
sub_menu.add_command(label='Color Themes')
# add the File menu to the menubar
file_menu.add_cascade(label="Preferences",menu=sub_menu)
# add Exit menu item
file_menu.add_separator()
file_menu.add_command(label='Exit',command=root.destroy)
menubar.add_cascade(label="File",menu=file_menu,underline=0)
# create the Help menu
help_menu = Menu(menubar,tearoff=0)
help_menu.add_command(label='Welcome')
help_menu.add_command(label='About...')
# add the Help menu to the menubar
menubar.add_cascade(label="Help",menu=help_menu, underline=0)
root.mainloop()
• Creating Tables
• A table is useful to display data in the form of rows and columns.
• Python does not provide a Table widget to create a table. But we can create a
table using alternate methods.
• For example, we can make a table by repeatedly displaying Entry widgets in the
form of rows and columns
• To create a table with 5 rows and 4 columns, we can use 2 for loops as:
for i in range(5):
for j in range (4):
• Inside these loops, we have to create an Entry widget by creating an object of
Entry class, as:
e = Entry(root, width=m, fg= 'color', font=('fontname', size, 'fontstyle'))
e = Entry(root, width=20, fg= 'blue', font=('Arial', 16, 'bold'))
• Now, we need logic to place this entry widget in rows and columns. This can be
done using grid() method to which we can pass row and column positions, as:
e.grid(row=i, column=j) # here i and j indicate row and column positions
• We can insert data into the Entry widget using insert() method, as:
e.insert (END, data)
• Here, 'END' indicates that the data con to append at the end of the previous
data in the Entry widget.
• To create a table using the data that is coming from a list.
• We have taken a list containing 5 tuples and each tuple contains 4 values which
indicate employee id number, name, city and salary.
• Hence we will have a table with 5 rows and 4 columns in each row.
• This program can be applied on the data coming from a database to display the
entire data in the form of a table.
• Program :A GUI Program to display a table with several rows and columns.
• # table creation
from tkinter import *
class MyTable:
def __init__(self, root):
# code for creating the table
for i in range(total_rows):
for j in range (total_cols):
self.e = Entry(root, width=20, fg='blue',font=('Arial', 16, 'bold'))
self.e.grid(row=i, column=j)
self.e.insert(END,lst[i][j])
# take the data
lst = [(101, 'Harshitha', 'Mangalore', 75000.70),
(102, 'Hitha', 'Mysore', 20000.50),
(103, 'Raveesh', 'Belthangady', 44500.75),
(104, 'Raksha', 'Bombay', 95500.00),
(105, 'Ravi','Chennai', 21786.40)]

# find the no. of rows and cols in the list


total_rows = len(lst)
total_cols = len (lst[0])

# create root window


root = Tk()
mt = MyTable(root)
root.mainloop()
Thank you

You might also like