Chapter 12 - GU Interface
Chapter 12 - GU Interface
Chapter 3 - GU Interface
GUI in Python
Python offers tkinter module to create graphics 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.
TK is used by Python programmers in developing GUI applications through Python's tkinter module.
1
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 1360 X 768, it indicates that the screen can accommodate 1360
pixels width-wise and 768 pixels height-wise.
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, hand1, 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 specify colors using
hexadecimal numbers in the format: #rrggbb# 8 bits per color #rrrgggbbb# 12 bits per color
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: [Link]()
After the canvas is created, we can draw any shapes on the canvas. For example, to create a line, we
can use create_line() method, as:
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_line() method returns an identification number.
To create an oval, we can use the create_oval() method. An oval is also called ellipse.
Program: A GUI program that demonstrates the creation of various shapes in canvas.
from tkinter import*
root = Tk() # create, root window
#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")
2
#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")
Output:
# add canvas to the root window
[Link]()
# wait for any events
[Link]()
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:
f= Frame(root, height=400, width=500, bg="yellow", cursor="cross")
Here, ‘f'’ is 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 be
displayed in the frame.
Once the frame is created, it should be added to the root window using the pack() method as
follows: [Link]()
Example Program: A GUI program to display a frame in the root window
from tkinter import *
root = Tk() # create root window Output:
[Link](“Frame") #give a title for root window
# create a frame as child to root window
f= Frame (root, height=400, width=500, bg="yellow",
cursor=”cross”)
[Link]() #attach the frame to root window
[Link]() #let the root window wait for any events
Canvas Frame
This is a container that is generally used to This is a container that is generally used to
draw shapes like lines, curves, arcs and circles. display widgets like buttons, check buttons
or menus.
We use Canvas class to create canvas. We use Frame class to create frames.
Example: c = Canvas(root, bg="blue", Example: f= Frame(root, height=400,
height=500, width=600, cursor='pencil') width=500, bg="yellow", cursor="cross")
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.
3
Widgets are eventful python objects that have a representation in the browser, often as a control like a
slider, textbox, etc.
The following are important widgets in Python:
Button Scrollbar Spinbox
Label Checkbutton Listbox
Message Radiobutton Menu
Text Entry
Working with Widgets
In general, working with widgets takes the following four steps.
1. Create the widget by creating an object of type class. Suppose we want to create a push button; we
can create an object to Button class as:
b = Button(f, text='My 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, following
is 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 tasks. As an example, let's
bind the button click with the function as:
[Link]('<Button-1>', buttonClick)
4. 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 the events as:
[Link]()
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')
Example: 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 foreground color and “fg” represents the back ground color of the button.
“activebackground” represents the background color when the button is clicked.
“activeforeground” represents the foreground color when the button is clicked.
4
We can also display an image on the button as:
# first load the image into filel
filel =PhotoImage(file="[Link]")
# create a push button with image
b = Button(f, image=file1, width=150, height=100, bg='yellow', fg='blue', ativebackground='green',
activeforeground='red')
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 buttonClick method using bind method as:
[Link](“<Button -1>”, buttonclick)
Here, <Button-1> represents the mouse left button that is linked withbuttonClick() 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 mouses 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.
Example Program
import tkinter as tk
# Function to be called when the button is clicked
def on_button_click(event):
print("You clicked me")
# Create the main window
root = [Link]()
[Link]("Button Inside Frame Example")
# Create a frame widget
frame = [Link](root, width=200, height=100, bg='lightgray')
[Link](padx=10, pady=10)
# Create a button widget inside the frame
button = [Link](frame, text="Click Me!")
[Link](pady=20)
# Bind the left mouse button click event (Button-1) to the on_button_click function
[Link]("<Button-1>", on_button_click)
# Start the Tkinter event loop
[Link]()
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 handles
function as:
D = Button (frame, 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 “bl”. Please observe the “command” option. Here, we are using the
lambda expression to pass the argument 1 to the button Click() 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
5
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.
Example:
import tkinter as tk
# Function to be called when the button is clicked, with a message argument
def on_button_click(message):
print(message)
# Create the main window
root = [Link]()
[Link]("Button with lambda Example")
# Create a frame widget
frame = [Link](root, width=200, height=100, bg='lightgray')
[Link](padx=10, pady=10)
# Create a button widget inside the frame, using lambda to pass an argument
button = [Link](frame, text="Click Me!", command=lambda: on_button_click ("You Clicked Me"))
[Link](pady=20)
# Start the Tkinter event loop
[Link]()
6
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.
Example: Output:
from tkinter import *
root = Tk()
f = Frame(root)
[Link](fill = X, expand = True)
b1 = Button(f, text = "Click me !")
[Link](side=LEFT, padx=10, pady=15)
b2 = Button(f, text = "Click me too")
[Link](side=RIGHT, padx=10, pady=15)
b3 = Button(f, text = "Click me Also!")
[Link](side=BOTTOM)
b4 = Button(f, text = "I Am also a Button")
[Link]() #by default TOP
[Link]()
Label Widget
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="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.
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:
m = 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.
Example:
from tkinter import *
class MyMessage:
def init (self, root):
self.f = Frame(root, height=350, width=500)
[Link](0)
[Link]()
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='dark goldenrod')
[Link](side=LEFT)
root = Tk()
mb = MyMessage(root)
[Link]()
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:
8
t = Text(root, width=20, height=10, font=('Verdana', 14, 'bold'), fg='blue', bg='yellow',
wrap=WORD)
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 break 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:
[Link](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='[Link]') # store [Link] into img object
t.image_create(END, image=[Link]) #append img to Text widget at the end
It is possible to mark 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 as: 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 as:
t.tag_config('start', background='red', foreground='white', font=('Lucida console', 20, 'bold italic'))
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 Scrollbar class as:
s = Scrollbar(root, orient=VERTICAL, command= [Link])
Here, 'orient' indicates whether it is a vertical scroll bar or horizontal scrollbar. The 'command' option
specifies to which widget this scroll bar should be connected.'[Link]' represents that the scroll bar is
connected to 't', [Link] widget and 'yview' is for vertical scrolling. [Link](yscrollcommand=[Link])
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:
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
[Link](END, "Text widget: this text is inserted into the Text widget.\nThis is
the second line widget.\nAnd this is the third line.\n")
# attach Text to the root Output:
[Link](side=LEFT)
# show image in the Text widget
[Link] = PhotoImage(file='[Link]')
self.t.image_create(END, image=[Link])
# create a tag with the name 'start'
self.t.tag_add('start', '1.0', '1.11')
# apply colors and font to the tag
9
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=[Link])
# attach the scroll bar to the Text widget
[Link](yscrollcommand=[Link])
# attach the scroll bar to the root window
[Link](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
[Link]()
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=[Link])
v = Scrollbar(root, orient=VERTICAL, bg='green', command=[Link])
After creating the scroll bar, it should be attached to the widget like Text widget or Listbox as:
[Link](xscrollcommand=[Link])
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: [Link](yscrollcommand=[Link])
Finally, the scroll bar should be attached to the root window using the pack() or grid() methods as:
[Link](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: [Link](side=RIGHT, fill=Y)
10
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='yellow', fg= 'green', font=('Georgia', 20, 'underline'), text='Java', variable=
var1, command=display)
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' will be 1, otherwise its value will be
0.
To retrieve the value from 'var1', we should use the get() method, as:
x = [Link]() # x value can be 1 or 0
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:
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. The
object of IntVar class can be created as:
var = IntVar()
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.
Entry Widget
Entry widget is useful to create a rectangular box that can be used to enter or display one line of text. An
Entry widget can be created as an object of Entry class as:
e1 = Entry(f, width=25, fg='blue', bg='yellow', font=('Arial', 14), show='*')
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:
[Link]("", [Link])
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):
Example Program:
from tkinter import *
class MyEntry:
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
[Link](0)
11
# attach the frame to root window
[Link]()
# labels
self.l1 = Label(self.f, text='Enter user name: ')
self.l2 = Label(self.f, 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 with stars
self.e2 = Entry(self.f, width=25, fg='blue', bg='yellow', font=('Arial', 14),
show="*")
# place labels and entry widgets in the frame
[Link](x=50, y=100)
[Link](x=200, y=100)
[Link](x=50, y=150)
[Link](x=200, y=150)
# Button to display the entered values
self.b = Button(self.f, text="Display", command=[Link])
[Link](x=200, y=200)
def display(self):
# retrieve the values from the entry widgets Output:
str1 = [Link]()
str2 = [Link]()
# display the values using labels
lbl1 = Label(self.f, text='Your name is: ' + str1)
[Link](x=50, y=250)
lbl2 = Label(self.f, text='Your password is: ' + str2)
[Link](x=50, y=280)
# create root window
root = Tk()
# create an object of MyEntry class
mb = MyEntry(root)
# the root window handles the mouse click event
[Link]()
Spinbox Widget
A Spinbox widget allows the user to select values from a given set
of values.
The values may be a range of numbers or a fixed set of strings.
The spin box appears as a long rectangle attached with arrowheads
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. To create a spin box with numbers ranging from 5 to
15, we can write the following statement:
s1 = Spinbox(f, from_= 5, to=15, textvariable=val1, width=15, fg='blue', bg='yellow', font= ('Arial',
14, 'bold'))
12
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="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 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:
[Link](0, 'Standford University')
[Link](1, ' Oxford University')
To bind the ListboxSelect event with a method, we can use the bind() method as:
[Link]('<>', on_select)
Example Program
from tkinter import *
class ListboxDemo:
def init (self, root):
self.f = Frame(root, width=700, height=400)
# let the frame not shrink
[Link](0)
# attach the frame to the root window
[Link]()
# create a label
[Link] = Label(self.f, text="Click one or more of the Universities below:",
font="Calibri 14")
[Link](x=50, y=50)
# create a list box with university names
[Link] = Listbox(self.f, font="Arial 12 bold", fg='blue', bg='yellow', height=8,
selectmode=MULTIPLE)
[Link](x=50, y=100)
# insert items into the listbox
universities = ["Mangalore University", "Bangalore University", "Mysore
University", "Kuvempu University", "Darwad University", "Central University"]
for university in universities:
[Link](END, university)
# bind the listbox select event to the on_select() method
[Link]('<<ListboxSelect>>', self.on_select)
13
# create a text box to display selected items
self.t = Text(self.f, width=40, height=6, wrap=WORD)
[Link](x=300, y=100)
def on_select(self, event):
# create an empty list to store selected items
[Link] = []
# get the indexes of the selected items
indexes = [Link]()
# retrieve the names of the items using the indexes and append them to the list
for i in indexes:
[Link]([Link](i))
# delete the previous content of the text box
[Link](1.0, END)
# insert the new contents (selected universities) into the text box
[Link](1.0, '\n'.join([Link]))
# create the root window Output:
root = Tk()
# set the title for the root window
[Link]("Listbox Demonstration")
# create an object of the ListboxDemo class
obj = ListboxDemo(root)
# start the Tkinter event loop
[Link]()
Menu Widget
A menu represents a group of items or options for the user to select from. For example, when we click on
'File' menu, it may display options like 'New', 'Open', 'Save', etc. We can select any option depending on
our requirements. 'New', 'Open', 'Save' - these options are called menu items. Thus, a menu is composed
of several menu items.
Similarly, 'Edit' is a menu with menu items like 'Cut', 'Copy', 'Paste', etc. Generally, we see menus
displayed in a bar, called menu bar.
To create a menu, we should use the following steps:
First of all, we should create a menu bar as a child to root window.
This is done using Menu class as: menubar = Menu(root)
This menu bar should be attached to the root window using config()
method as: [Link](menu=menubar)
The next step is to create a menu with a group of menu items. For this purpose, first of all we should
create Menu class object as: filemenu = Menu(root, tearoff=0)
The option 'tearoff' can be 0 or [Link] this option is 1, the menu can be torn off.
The next step is to add menu items to the filemenu object using the add_command() method as:
filemenu.add_command(label="New", command=donothing)
When we want to display a horizontal line that separates a group of menu items from another group of
menu items, we can use the add_separator() method, as given in the following
statement: filemenu.add_separator()
After adding all menu items to filemenu object, we should give it a name and add it to menu bar using
add_cascade() method as:
menubar.add_cascade(label="File", menu=filemenu)
The 'menu' option tells that the 'File' menu is composed of all menu items that are added already to
filemenu object.
14