0% found this document useful (0 votes)
0 views93 pages

Advance Python Unit - 1

The document provides an overview of Tkinter, the standard GUI library for Python, detailing its features and how to create GUI applications. It explains the process of creating a main window, adding widgets, and managing layout using geometry managers like pack(), grid(), and place(). Additionally, it describes various widgets available in Tkinter, such as buttons, labels, and canvases, along with their functionalities and usage examples.

Uploaded by

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

Advance Python Unit - 1

The document provides an overview of Tkinter, the standard GUI library for Python, detailing its features and how to create GUI applications. It explains the process of creating a main window, adding widgets, and managing layout using geometry managers like pack(), grid(), and place(). Additionally, it describes various widgets available in Tkinter, such as buttons, labels, and canvases, along with their functionalities and usage examples.

Uploaded by

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

Programming in Advance Python – 2

JKM BCA College


Python Tkinter

JKM BCA College


 Tkinter is the standard GUI library for Python.
 Python when combined with Tkinter provides a fast
and easy way to create GUI applications.
 Tkinter provides a powerful object-oriented interface
to the Tk GUI toolkit.
 You don’t need to worry about the installation of the
Tkinter module separately as it comes with Python
already.
 Creating a GUI application using Tkinter is an easy task. All
you need to do is perform the following steps −
◦ Import the Tkinter module.
◦ Create the GUI application main window.
◦ Add one or more of widgets to the window.
◦ Enter the main event loop to take action against each event
triggered by the user.

JKM BCA College


 Example
import tkinter
#creating the application main window.
top = tkinter.Tk()
# Entering the event main loop
top.mainloop()
 Output

JKM BCA College


 Widgets in Tkinter are the elements of GUI
application which provides various controls (such
as Labels, Buttons, ComboBoxes, CheckBoxes,
MenuBars, RadioButtons and many more) to users
to interact with the application.
 Each separate widget is a Python object. When
creating a widget, you must pass its parent as a
parameter to the widget creation function.
The only exception is the “root” window, which is
the top-level window that will contain everything
else and it does not have a parent.
 There are currently 15 types of widgets in Tkinter.
We present these widgets as well as a brief
description in the following table

JKM BCA College


Sr.No. Operator & Description

1 Button
The Button widget is used to display buttons in your application.
2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in
your application.
3 Checkbutton
The Checkbutton widget is used to display a number of options as checkboxes. The user can
select multiple options at a time.
4 Entry
The Entry widget is used to display a single-line text field for accepting values from a user.
5 Frame
The Frame widget is used as a container widget to organize other widgets.
6 Label
The Label widget is used to provide a single-line caption for other widgets. It can also contain
images.
7 Listbox
The Listbox widget is used to provide a list of options to a user.

JKM BCA College


8 Menubutton
The Menubutton widget is used to display menus in your application.
9 Menu
The Menu widget is used to provide various commands to a user. These commands are
contained inside Menubutton.
10 Message
The Message widget is used to display multiline text fields for accepting values from a user.
11 Radiobutton
The Radiobutton widget is used to display a number of options as radio buttons. The user can
select only one option at a time.
12 Scale
The Scale widget is used to provide a slider widget.
13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.
14 Text
The Text widget is used to display text in multiple lines.

JKM BCA College


15 Toplevel
The Toplevel widget is used to provide a separate window container.
16 Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to
select from a fixed number of values.
17 PanedWindow
A PanedWindow is a container widget that may contain any number of panes, arranged
horizontally or vertically.
18 LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer or container
for complex window layouts.
19 tkMessageBox
This module is used to display message boxes in your applications.

JKM BCA College


 Creating a new widget doesn’t mean that it will appear on the screen. To
display it, we need to call a special method: either grid or place.

Method Description

pack() The Pack geometry manager packs widgets in rows or columns.

The Grid geometry manager puts the widgets in a 2-dimensional


table.
grid()
The master widget is split into a number of rows and columns, and
each “cell” in the resulting table can hold a widget.

The Place geometry manager is the simplest of the three general


geometry managers provided in Tkinter.
place()
It allows you explicitly set the position and size of a window, either in
absolute terms, or relative to another window.

JKM BCA College


from tkinter import *  Output :
# create root window
root = Tk()

# frame inside root window


frame = Frame(root)

# geometry method
frame.pack()

# button inside frame which is


# inside root
button = Button(frame, text ='Geek')
button.pack()

# Tkinter event loop


root.mainloop()

JKM BCA College


 The pack() widget is used to organize widget in the block. The
positions widgets added to the python application using the
pack() method can be controlled by using the various options
specified in the method call.
 However, the controls are less and widgets are generally added
in the less organized manner.
 syntax
◦ widget.pack(options)
 A list of possible options that can be passed in pack() is given
below.
◦ expand: If the expand is set to true, the widget expands to fill any
space.
◦ Fill: By default, the fill is set to NONE. However, we can set it to X or Y
to determine whether the widget contains any extra space.
◦ size: it represents the side of the parent to which the widget is to be
placed on the window.

JKM BCA College


from tkinter import *
parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = "Black", fg = "black")
greenbutton.pack( side = RIGHT )
bluebutton = Button(parent, text = "Blue", fg = "blue")
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = "Green", fg = "red")
blackbutton.pack( side = BOTTOM)
parent.mainloop()

JKM BCA College


 The grid() geometry manager organizes the widgets in the tabular form. We can
specify the rows and columns as the options in the method call. We can also
specify the column span (width) or rowspan(height) of a widget.
 This is a more organized way to place the widgets to the python application.
 Syntax
◦ widget.grid(options)
 A list of options that can be passed inside the grid() method is given below.
◦ Column
The column number in which the widget is to be placed. The leftmost column is
represented by 0.
◦ Columnspan
The width of the widget. It represents the number of columns up to which, the column is
expanded.
◦ ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's border.
◦ padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
◦ row
The row number in which the widget is to be placed. The topmost row is represented by 0.
◦ rowspan
The height of the widget, i.e. the number of the row up to which the widget is expanded.
◦ Sticky
If the cell is larger than a widget, then sticky is used to specify the position of the widget
inside the cell. It may be the concatenation of the sticky letters representing the position of
the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.

JKM BCA College


from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop()

JKM BCA College


 The place() geometry manager organizes the widgets to
the specific x and y coordinates.
 Syntax
◦ widget.place(options)
 A list of possible options is given below.
◦ Anchor: It represents the exact position of the widget within the
container. The default value (direction) is NW (the upper left
corner)
◦ bordermode: The default value of the border type is INSIDE that
refers to ignore the parent's inside the border. The other option is
OUTSIDE.
◦ height, width: It refers to the height and width in pixels.
◦ relheight, relwidth: It is represented as the float between 0.0 and
1.0 indicating the fraction of the parent's height and width.
◦ relx, rely: It is represented as the float between 0.0 and 1.0 that is
the offset in the horizontal and vertical direction.
◦ x, y: It refers to the horizontal and vertical offset in the pixels.

JKM BCA College


from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()

JKM BCA College


 The Button widget is used to add buttons in a
Python application. These buttons can display
text or images that convey the purpose of the
buttons. You can attach a function or a method
to a button which is called automatically when
you click the button.
 Syntax
◦ w = Button ( master, option=value, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used
options for this widget. These options can be used as
key-value pairs separated by commas.

JKM BCA College


 Some options are as follows:
◦ activebackground: to set the background color
when button is under the cursor.
◦ activeforeground: to set the foreground color when
button is under the cursor.
◦ bg: to set he normal background color.
◦ command: to call a function.
◦ font: to set the font on the button label.
◦ image: to set the image on the button.
◦ width: to set the width of the button.
◦ height: to set the height of the button.

JKM BCA College


Methods

Following are commonly used methods for this widget −

Sr.No. Method & Description

1 flash()
Causes the button to flash several times between active and normal colors.
Leaves the button in the state it was in originally. Ignored if the button is
disabled.

2 invoke()
Calls the button's callback, and returns what that function returns. Has no
effect if the button is disabled or there is no callback.

JKM BCA College


import tkinter
from tkinter import messagebox
top = tkinter.Tk()
def helloCallBack():
messagebox.showinfo( "Hello Python", "Hello World")
B = tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()

JKM BCA College


 The tkMessageBox module is used to display message boxes in
your applications. This module provides a number of functions
that you can use to display an appropriate message.
 Some of these functions are showinfo, showwarning, showerror,
askquestion, askokcancel, askyesno, and askretryignore.
 Syntax
◦ tkMessageBox.FunctionName(title, message [, options])
 Parameters
◦ FunctionName − This is the name of the appropriate message box
function.
◦ title − This is the text to be displayed in the title bar of a message
box.
◦ message − This is the text to be displayed as a message.
◦ options: There are two options that can be used are:
default: This option is used to specify the default button like
ABORT, RETRY, or IGNORE in the message box.
parent: This option is used to specify the window on top of which
the message box is to be displayed.

JKM BCA College


 Function_Name:
There are functions or methods available in the
messagebox widget.
◦ showinfo(): Show some relevant information to the user.
◦ showwarning(): Display the warning to the user.
◦ showerror(): Display the error message to the user.
◦ askquestion(): Ask question and user has to answered in
yes or no.
◦ askokcancel(): Confirm the user’s action regarding some
application activity.
◦ askyesno(): User can answer in yes or no for some
action.
◦ askretrycancel(): Ask the user about doing a particular
task again or not.

JKM BCA College


from tkinter import *
from tkinter import messagebox

root = Tk()
root.geometry("300x200")

w = Label(root, text ='GeeksForGeeks', font = "50")


w.pack()

messagebox.showinfo("showinfo", "Information")
messagebox.showwarning("showwarning", "Warning")
messagebox.showerror("showerror", "Error")
messagebox.askquestion("askquestion", "Are you sure?")
messagebox.askokcancel("askokcancel", "Want to continue?")
messagebox.askyesno("askyesno", "Find the value?")
messagebox.askretrycancel("askretrycancel", "Try again?")

root.mainloop()

JKM BCA College


JKM BCA College
 The Canvas is a rectangular area intended for
drawing pictures or other complex layouts.
You can place graphics, text, widgets or
frames on a Canvas.
 Syntax
◦ w = Canvas ( master, option=value, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used
options for this widget. These options can be used
as key-value pairs separated by commas.

JKM BCA College


 Some options are as follows:
◦ bd: to set the border width in pixels.
◦ bg: to set the normal background color.
◦ cursor: to set the cursor used in the canvas.
◦ highlightcolor: to set the color shown in the focus
highlight.
◦ width: to set the width of the widget.
◦ height: to set the height of the widget.

JKM BCA College


 The Canvas widget can support the following
standard items −
 arc − Creates an arc item, which can be a chord,
a pieslice or a simple arc.
coord = 10, 50, 240, 210
arc = canvas.create_arc(coord, start=0, extent=150, fill="blue")
 image − Creates an image item, which can be an
instance of either the BitmapImage or the
PhotoImage classes.
filename = PhotoImage(file = "sunshine.gif")
image = canvas.create_image(50, 50, anchor=NE, image=filename)
 line − Creates a line item.
line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn, options)

JKM BCA College


 oval − Creates a circle or an ellipse at the
given coordinates. It takes two pairs of
coordinates; the top left and bottom right
corners of the bounding rectangle for the
oval.
oval = canvas.create_oval(x0, y0, x1, y1, options)
 polygon − Creates a polygon item that must
have at least three vertices.
oval = canvas.create_polygon(x0, y0, x1, y1,...xn, yn, options)

JKM BCA College


import tkinter
top = tkinter.Tk()
C = tkinter.Canvas(top, bg="blue", height=250, width=300)
coord = 10, 50, 240, 210
arc = C.create_arc(coord, start=0, extent=150, fill="red")
C.pack()
top.mainloop()

JKM BCA College


 The Checkbutton widget is used to display a
number of options to a user as toggle
buttons. The user can then select one or
more options by clicking the button
corresponding to each option.
 Syntax
◦ w = Checkbutton ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used
options for this widget. These options can be used
as key-value pairs separated by commas.

JKM BCA College


 Some of the options are listed below.
◦ Title: To set the title of the widget.
◦ activebackground: to set the background color
when widget is under the cursor.
◦ activeforeground: to set the foreground color when
widget is under the cursor.
◦ bg: to set he normal backgrouSteganographyBreak
◦ command: to call a function.
◦ font: to set the font on the button label.
◦ image: to set the image on the widget.

JKM BCA College


 Following are commonly used methods for this widget −

Sr.No. Method & Description

1 deselect()
Clears (turns off) the checkbutton.
2 flash()
Flashes the checkbutton a few times between its active and normal
colors, but leaves it the way it started.

3 invoke()
You can call this method to get the same actions that would occur if the
user clicked on the checkbutton to change its state.

4 select()
Sets (turns on) the checkbutton.
5 toggle()
Clears the checkbutton if set, sets it if cleared.

JKM BCA College


from tkinter import *
Import messagebox
import tkinter
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1, offvalue = 0,
height=5, width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, offvalue = 0,
height=5, width = 20)
C1.pack()
C2.pack()
top.mainloop()

JKM BCA College


 The Entry widget is used to accept single-line text
strings from a user.
 If you want to display multiple lines of text that can
be edited, then you should use the Text widget.
 If you want to display one or more lines of text that
cannot be modified by the user, then you should use
the Label widget.
 Syntax
◦ w = Entry( master, option=value)
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used options
for this widget. These options can be used as key-value
pairs separated by commas.

JKM BCA College


 Some of the options are listed below.
◦ bd: to set the border width in pixels.
◦ bg: to set the normal background color.
◦ cursor: to set the cursor used.
◦ command: to call a function.
◦ highlightcolor: to set the color shown in the focus
highlight.
◦ width: to set the width of the button.
◦ height: to set the height of the button.

JKM BCA College


 Following are commonly used methods for this widget −

Sr.No. Method & Description


1 delete ( first, last=None )
Deletes characters from the widget, starting with the one at index first, up to but
not including the character at position last. If the second argument is omitted, only
the single character at position first is deleted.
2 get()
Returns the entry's current text as a string.
3 icursor ( index )
Set the insertion cursor just before the character at the given index.
4 index ( index )
Shift the contents of the entry so that the character at the given index is the
leftmost visible character. Has no effect if the text fits entirely within the entry.
5 insert ( index, s )
Inserts string s before the character at the given index.
6 select_adjust ( index )
This method is used to make sure that the selection includes the character at the
specified index.

JKM BCA College


Sr.No. Method & Description
7 select_clear()
Clears the selection. If there isn't currently a selection, has no effect.
8 select_from ( index )
Sets the ANCHOR index position to the character selected by index, and selects that
character.
9 select_present()
If there is a selection, returns true, else returns false.
10 select_range ( start, end )
Sets the selection under program control. Selects the text starting at the start index,
up to but not including the character at the end index. The start position must be
before the end position.
11 select_to ( index )
Selects all the text from the ANCHOR position up to but not including the character
at the given index.

JKM BCA College


from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()

JKM BCA College


 The Frame widget is very important for the process of
grouping and organizing other widgets in a somehow
friendly way. It works like a container, which is responsible
for arranging the position of other widgets.
 It uses rectangular areas in the screen to organize the
layout and to provide padding of these widgets. A frame
can also be used as a foundation class to implement
complex widgets.
 Syntax
◦ w = Frame ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated
by commas.

JKM BCA College


 Some of the options are listed below.
◦ highlightcolor: To set the color of the focus
highlight when widget has to be focused.
◦ bd: to set the border width in pixels.
◦ bg: to set the normal background color.
◦ cursor: to set the cursor used.
◦ width: to set the width of the widget.
◦ height: to set the height of the widget.

JKM BCA College


From tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()

bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )

redbutton = Button(frame, text="Red", fg="red“)


redbutton.pack( side = LEFT)
greenbutton = Button(frame, text="Brown", fg="brown“)
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text="Blue", fg="blue")
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text="Black", fg="black")
blackbutton.pack( side = BOTTOM)

root.mainloop()

JKM BCA College


 This widget implements a display box where you can
place text or images. The text displayed by this
widget can be updated at any time you want.
 It is also possible to underline part of the text (like to
identify a keyboard shortcut) and span the text
across multiple lines.
 Syntax
 Here is the simple syntax to create this widget −
◦ w = Label ( master, option=value)
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used options
for this widget. These options can be used as key-value
pairs separated by commas.

JKM BCA College


 Some of the options are listed below.
◦ bg: to set he normal background color.
◦ bg to set he normal background color.
◦ command: to call a function.
◦ font: to set the font on the button label.
◦ image: to set the image on the label
◦ width: to set the width of the label
◦ height” to set the height of the label.

JKM BCA College


from tkinter import *
root = Tk()
w = Label(root, text='GeeksForGeeks.org!')
w.pack()
root.mainloop()

JKM BCA College


 The Listbox widget is used to display a list of
items from which a user can select a number
of items.
 Syntax
◦ w = Listbox ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used
options for this widget. These options can be used
as key-value pairs separated by commas.

JKM BCA College



Some of the options ar listed below
◦ bg The normal background color displayed behind the label and indicator.
◦ bd The size of the border around the indicator. Default is 2 pixels.
◦ cursor: The cursor that appears when the mouse is over the listbox.
◦ font: The font used for the text in the listbox.
◦ fg: The color used for the text in the listbox.
◦ height :Number of lines (not pixels!) shown in the listbox. Default is 10.
◦ highlightcolor: Color shown in the focus highlight when the widget has the
focus.
◦ highlightthickness: Thickness of the focus highlight.
◦ elief: Selects three-dimensional border shading effects. The default is
SUNKEN.
◦ selectbackground: The background color to use displaying selected text.

JKM BCA College


◦ selectmode: Determines how many items can be selected, and how mouse
drags affect the selection −
 BROWSE − Normally, you can only select one line out of a listbox. If you
click on an item and then drag to a different line, the selection will
follow the mouse. This is the default.
 SINGLE − You can only select one line, and you can't drag the
mouse.wherever you click button 1, that line is selected.
 MULTIPLE − You can select any number of lines at once. Clicking on any
line toggles whether or not it is selected.
 EXTENDED − You can select any adjacent group of lines at once by
clicking on the first line and dragging to the last line.
◦ width: The width of the widget in characters. The default is 20.

JKM BCA College


 Methods on listbox objects include

Sr.No. Option & Description


1 activate ( index )
Selects the line specifies by the given index.
2 curselection()
Returns a tuple containing the line numbers of the selected element or elements,
counting from 0. If nothing is selected, returns an empty tuple.
3 delete ( first, last=None )
Deletes the lines whose indices are in the range [first, last]. If the second
argument is omitted, the single line with index first is deleted.
4 get ( first, last=None )
Returns a tuple containing the text of the lines with indices from first to last,
inclusive. If the second argument is omitted, returns the text of the line closest to
first.
5 index ( i )
If possible, positions the visible part of the listbox so that the line containing
index i is at the top of the widget.

JKM BCA College


Sr.No. Option & Description
6 insert ( index, *elements )
Insert one or more new lines into the listbox before the line specified by index.
Use END as the first argument if you want to add new lines to the end of the
listbox.
7 nearest ( y )
Return the index of the visible line closest to the y-coordinate y relative to the
listbox widget.
8 see ( index )
Adjust the position of the listbox so that the line referred to by index is visible.
9 size()
Returns the number of lines in the listbox.
10 xview()
To make the listbox horizontally scrollable, set the command option of the
associated horizontal scrollbar to this method.
13 yview()
To make the listbox vertically scrollable, set the command option of the
associated vertical scrollbar to this method.

JKM BCA College


from tkinter import *
Import messagebox
Import tkinter

top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")

Lb1.pack()
top.mainloop()

JKM BCA College


 A menubutton is the part of a drop-down menu
that stays on the screen all the time. Every
menubutton is associated with a Menu widget
that can display the choices for that menubutton
when the user clicks on it.
 Syntax
◦ w = Menubutton ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used
options for this widget. These options can be used as
key-value pairs separated by commas.

JKM BCA College


 Some of them are listed below.
◦ activebackground: To set the background when mouse is
over the widget.
◦ activeforeground: To set the foreground when mouse is
over the widget.
◦ bg: to set he normal background color.
◦ bd: to set the size of border around the indicator.
◦ cursor: To appear the cursor when the mouse over the
menubutton.
◦ image: to set the image on the widget.
◦ width: to set the width of the widget.
◦ height: to set the height of the widget.
◦ highlightcolor: To set the color of the focus highlight
when widget has to be focused.

JKM BCA College


from tkinter import *

top = Tk()
mb = Menubutton ( top, text = "GfG")
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
cVar = IntVar()
aVar = IntVar()
mb.menu.add_checkbutton ( label ='Contact', variable = cVar )
mb.menu.add_checkbutton ( label = 'About', variable = aVar )
mb.pack()
top.mainloop()

JKM BCA College


 The goal of this widget is to allow us to create all kinds of
menus that can be used by our applications. The core
functionality provides ways to create three menu types:
pop-up, toplevel and pull-down.
 It is also possible to use other extended widgets to
implement new types of menus, such as
the OptionMenu widget, which implements a special type
that generates a pop-up list of items within a selection.
 Syntax
◦ w = Menu ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated
by commas.

JKM BCA College


 Some of them are listed below.
◦ title: To set the title of the widget.
◦ activebackground: to set the background color
when widget is under the cursor.
◦ activeforeground: to set the foreground color when
widget is under the cursor.
◦ bg: to set he normal background color.
◦ command: to call a function.
◦ font: to set the font on the button label.
◦ image: to set the image on the widget.

JKM BCA College


Sr.No Option & Description
.
1 add_command (options)
Adds a menu item to the menu.
2 add_radiobutton( options )
Creates a radio button menu item.
3 add_checkbutton( options )
Creates a check button menu item.
4 add_cascade(options)
Creates a new hierarchical menu by associating a given menu to a parent
menu
5 add_separator()
Adds a separator line to the menu.
6 add( type, options )
Adds a specific type of menu item to the menu.

JKM BCA College


7 delete( startindex [, endindex ])
Deletes the menu items ranging from startindex to endindex.
8 entryconfig( index, options )
Allows you to modify a menu item, which is identified by the index, and
change its options.
9 index(item)
Returns the index number of the given menu item label.
10 insert_separator ( index )
Insert a new separator at the position specified by index.
11 invoke ( index )
Calls the command callback associated with the choice at position index.
If a checkbutton, its state is toggled between set and cleared; if a
radiobutton, that choice is set.
12 type ( index )
Returns the type of the choice specified by index: either "cascade",
"checkbutton", "command", "radiobutton", "separator", or "tearoff".

JKM BCA College


from tkinter import *

root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()

JKM BCA College


 This widget provides a multiline and noneditable
object that displays texts, automatically breaking
lines and justifying their contents.
 Its functionality is very similar to the one provided by
the Label widget, except that it can also automatically
wrap the text, maintaining a given width or aspect
ratio.
 Syntax
◦ w = Message ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used options
for this widget. These options can be used as key-value
pairs separated by commas.

JKM BCA College


 Some of them are listed below.
◦ bd: to set the border around the indicator.
◦ bg: to set he normal background color.
◦ font: to set the font on the button label.
◦ image: to set the image on the widget.
◦ width: to set the width of the widget.
◦ height: to set the height of the widget.

JKM BCA College


from tkinter import *
main = Tk()
ourMessage ='This is our Message'
messageVar = Message(main, text = ourMessage)
messageVar.config(bg='lightgreen')
messageVar.pack( )
main.mainloop( )

JKM BCA College


 This widget implements a multiple-choice button,
which is a way to offer many possible selections to
the user and lets user choose only one of them.
 In order to implement this functionality, each group
of radiobuttons must be associated to the same
variable and each one of the buttons must symbolize
a single value. You can use the Tab key to switch
from one radionbutton to another.
 Syntax
◦ w = Radiobutton ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used options
for this widget. These options can be used as key-value
pairs separated by commas.

JKM BCA College


 Some of them are listed below.
◦ activebackground: to set the background color
when widget is under the cursor.
◦ activeforeground: to set the foreground color when
widget is under the cursor.
◦ bg: to set he normal background color.
◦ command: to call a function.
◦ font: to set the font on the button label.
◦ image: to set the image on the widget.
◦ width: to set the width of the label in characters.
◦ height: to set the height of the label in characters.

JKM BCA College


Sr.No. Method & Description
1 deselect()
Clears (turns off) the radiobutton.
2 flash()
Flashes the radiobutton a few times between its active and normal colors,
but leaves it the way it started.

3 invoke()
You can call this method to get the same actions that would occur if the
user clicked on the radiobutton to change its state.

4 select()
Sets (turns on) the radiobutton.

JKM BCA College


from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)
mainloop()

JKM BCA College


 The Scale widget provides a graphical slider
object that allows you to select values from a
specific scale.
 Syntax
◦ w = Scale ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used
options for this widget. These options can be used
as key-value pairs separated by commas.

JKM BCA College


 Some of them are listed below.
◦ cursor: To change the cursor pattern when the mouse is
over the widget.
◦ activebackground: To set the background of the widget
when mouse is over the widget.
◦ bg: to set he normal background color.
◦ orient: Set it to HORIZONTAL or VERTICAL according to
the requirement.
◦ from_: To set the value of one end of the scale range.
◦ to: To set the value of the other end of the scale range.
◦ image: to set the image on the widget.
◦ width: to set the width of the widget.

JKM BCA College


Sr.No. Method & Description

1 get()
This method returns the current value of the scale.
2 set ( value )
Sets the scale's value.

JKM BCA College


from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()

JKM BCA College


 This widget provides a slide controller that is
used to implement vertical scrolled widgets, such
as Listbox, Text and Canvas. Note that you can
also create horizontal scrollbars on Entry
widgets.
 Syntax
◦ w = Scrollbar ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used
options for this widget. These options can be used as
key-value pairs separated by commas.

JKM BCA College


 Some of them are listed below.
◦ width: to set the width of the widget.
◦ activebackground: To set the background when
mouse is over the widget.
◦ bg: to set he normal background color.
◦ bd: to set the size of border around the indicator.
◦ cursor: To appear the cursor when the mouse over
the menubutton.

JKM BCA College


Sr.No. Method & Description

1 get()
Returns two numbers (a, b) describing the current position of the slider.
The a value gives the position of the left or top edge of the slider, for
horizontal and vertical scrollbars respectively; the b value gives the
position of the right or bottom edge.

2 set ( first, last )


To connect a scrollbar to another widget w, set w's xscrollcommand or
yscrollcommand to the scrollbar's set() method. The arguments have the
same meaning as the values returned by the get() method.

JKM BCA College


from tkinter import *
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )
mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert(END, 'This is line number' + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()

JKM BCA College


 Text widgets provide advanced capabilities that allow you
to edit a multiline text and format the way it has to be
displayed, such as changing its color and font.
 You can also use elegant structures like tabs and marks to
locate specific sections of the text, and apply changes to
those areas. Moreover, you can embed windows and
images in the text because this widget was designed to
handle both plain and formatted text.
 Syntax
◦ w = Text ( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated
by commas.

JKM BCA College


 Some of them are listed below.
◦ highlightcolor: To set the color of the focus
highlight when widget has to be focused.
◦ insertbackground: To set the background of the
widget.
◦ bg: to set he normal background color.
◦ font: to set the font on the button label.
◦ image: to set the image on the widget.
◦ width: to set the width of the widget.
◦ height: to set the height of the widget.

JKM BCA College


Sr.No. Methods & Description

1 delete(startindex [,endindex])
This method deletes a specific character or a range of text.
2 get(startindex [,endindex])
This method returns a specific character or a range of text.
3 index(index)
Returns the absolute value of an index based on the given index.
4 insert(index [,string]...)
This method inserts strings at the specified index location.
5 see(index)
This method returns true if the text located at the index position is
visible.

JKM BCA College


from tkinter import *
root = Tk()
T = Text(root, height=2, width=30)
T.pack()
T.insert(END, 'GeeksforGeeks\nBEST WEBSITE\n')
mainloop()

JKM BCA College


 Toplevel widgets work as windows that are
directly managed by the window manager. They
do not necessarily have a parent widget on top of
them.
 Your application can use any number of top-level
windows.
 Syntax
◦ w = Toplevel ( option, ... )
 Parameters
◦ options − Here is the list of most commonly used
options for this widget. These options can be used as
key-value pairs separated by commas.

JKM BCA College


 Some of them are listed below.
◦ bg: to set he normal background color.
◦ bd: to set the size of border around the indicator.
◦ cursor: To appear the cursor when the mouse over
the menubutton.
◦ width: to set the width of the widget.
◦ height: to set the height of the widget.

JKM BCA College


Sr.No. Methods & Description
1 deiconify()
Displays the window, after using either the iconify or the withdraw
methods.
2 frame()
Returns a system-specific window identifier.
3 group(window)
Adds the window to the window group administered by the given
window.
4 iconify()
Turns the window into an icon, without destroying it.
5 protocol(name, function)
Registers a function as a callback which will be called for the given
protocol.
6 iconify()
Turns the window into an icon, without destroying it.

JKM BCA College


7 state()
Returns the current state of the window. Possible values are normal,
iconic, withdrawn and icon.
8 transient([master])
Turns the window into a temporary(transient) window for the given
master or to the window's parent, when no argument is given.
9 withdraw()
Removes the window from the screen, without destroying it.
10 maxsize(width, height)
Defines the maximum size for this window.
11 minsize(width, height)
Defines the minimum size for this window.
12 positionfrom(who)
Defines the position controller.
13 resizable(width, height)
Defines the resize flags, which control whether the window can be
resized.
14 sizefrom(who)
Defines the size controller.
15 title(string)
Defines the window title.

JKM BCA College


from tkinter import *
root = Tk()
root.title('GfG')
top = Toplevel()
top.title('Python')
top.mainloop()

JKM BCA College


 The Spinbox widget is a variant of the
standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
 Syntax
◦ w = Spinbox( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used
options for this widget. These options can be used
as key-value pairs separated by commas.

JKM BCA College


 Some of them are listed below.
◦ bg: to set he normal background color.
◦ bd: to set the size of border around the indicator.
◦ cursor: To appear the cursor when the mouse over the
menubutton.
◦ command: To call a function.
◦ width: to set the width of the widget.
◦ activebackground: To set the background when mouse is
over the widget.
◦ disabledbackground: To disable the background when
mouse is over the widget.
◦ from_: To set the value of one end of the range.
◦ to: To set the value of the other end of the range.

JKM BCA College


Sr.No. Methods & Description

1 delete(startindex [,endindex])
This method deletes a specific character or a range of text.
2 get(startindex [,endindex])
This method returns a specific character or a range of text.
3 identify(x, y)
Identifies the widget element at the given location.
4 index(index)
Returns the absolute value of an index based on the given index.
5 insert(index [,string]...)
This method inserts strings at the specified index location.
6 invoke(element)
Invokes a spinbox button

JKM BCA College


from tkinter import *
master = Tk()
w = Spinbox(master, from_ = 0, to = 10)
w.pack()
mainloop()

JKM BCA College


 A PanedWindow is a container widget that may contain any
number of panes, arranged horizontally or vertically.
 Each pane contains one widget and each pair of panes is
separated by a movable (via mouse movements) sash.
Moving a sash causes the widgets on either side of the
sash to be resized.
 Syntax
◦ w = PanedWindow( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated
by commas.

JKM BCA College


 Some of them are listed below.
◦ bg: to set he normal background color.
◦ bd: to set the size of border around the indicator.
◦ cursor: To appear the cursor when the mouse over
the menubutton.
◦ width: to set the width of the widget.
◦ height: to set the height of the widget.

JKM BCA College


Sr.No. Methods & Description

1 add(child, options)
Adds a child window to the paned window.
2 get(startindex [,endindex])
This method returns a specific character or a range of text.
3 config(options)
Modifies one or more widget options. If no options are given, the
method returns a dictionary containing all current option values.

JKM BCA College


from tkinter import *
m1 = PanedWindow()
m1.pack(fill = BOTH, expand = 1)
left = Entry(m1, bd = 5)
m1.add(left)
m2 = PanedWindow(m1, orient = VERTICAL)
m1.add(m2)
top = Scale( m2, orient = HORIZONTAL)
m2.add(top)
mainloop()

JKM BCA College


 A labelframe is a simple container widget. Its
primary purpose is to act as a spacer or container
for complex window layouts.
 This widget has the features of a frame plus the
ability to display a label.
 Syntax
◦ w = LabelFrame( master, option, ... )
 Parameters
◦ master − This represents the parent window.
◦ options − Here is the list of most commonly used
options for this widget. These options can be used as
key-value pairs separated by commas.

JKM BCA College



Some of them are listed below
◦ bg: The normal background color displayed behind the label and indicator.
◦ bd: The size of the border around the indicator. Default is 2 pixels.
◦ cursor: If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor will change to that pattern when it is over the checkbutton.
◦ font: The vertical dimension of the new frame.
◦ height: The vertical dimension of the new frame.
◦ labelAnchor: Specifies where to place the label.
◦ highlightbackground: Color of the focus highlight when the frame does
not have focus.
◦ highlightcolor: Color shown in the focus highlight when the frame has the
focus.
◦ highlightthickness: Thickness of the focus highlight.
◦ relief: With the default value, relief=FLAT, the checkbutton does not stand
out from its background. You may set this option to any of the other styles
◦ text: Specifies a string to be displayed inside the widget.
◦ width: Specifies the desired width for the window.

JKM BCA College


from Tkinter import *
root = Tk()

labelframe = LabelFrame(root, text="This is a LabelFrame")


labelframe.pack(fill="both", expand="yes")

left = Label(labelframe, text="Inside the LabelFrame")


left.pack()

root.mainloop()

JKM BCA College

You might also like