0% found this document useful (0 votes)
9 views40 pages

Module5 Python GUI

Python notes

Uploaded by

nadafathima331
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)
9 views40 pages

Module5 Python GUI

Python notes

Uploaded by

nadafathima331
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/ 40

MODULE V GUI PROGRAMMING

Python GUI – tkinter


There are many graphical user interface (GUI) toolkits that you can use with
the Python programming language. The big three are Tkinter, wxPython, and
JPython. Each of these toolkits will work with Windows, macOS, and Linux.A
graphical user interface is an application that has buttons, windows, and lots of other
widgets that the user can use to interact with your application.A good example would
be a web browser. It has buttons, tabs, and a main window where all the content
loads.
Python offers multiple options for developing GUI (Graphical User Interface).
Out of all the GUI methods, tkinter is the most commonly used method.It is a
standard Python interface to the Tk GUI toolkit shipped with Python. Python with
tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI
using tkinter is an easy task.
To create a tkinter app:
1.Importing the module – tkinter
2.Create the GUI application main window (container)
3.Add any number of widgets to the main window
4.Enter the main event loop to take action against each event triggered by the user
Note:
Importing tkinter is same as importing any other module in the Python code. Note
that the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.
There are two main methods used which the user needs to remember while creating
the Python application with GUI.
1.Tk(screenName=None, baseName=None, className=’Tk’, useTk=1):
To create a main window, tkinter offers a method Tk() .
To change the name of the window, you can change the className to the desired
one. The basic code used to create the main window of the application is:
m=tkinter.Tk() where m is the name of the main window object
2. mainloop():
There is a method known by the name mainloop() is used when your application is
ready to run.
mainloop() is an infinite loop used to run the application, wait for an event to occur
and process the event as long as the window is not closed.
m.mainloop()
Eg:
import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()
OUTPUT

tkinter also offers access to the geometric configuration of the widgets which can
organize the widgets in the parent windows. There are mainly three geometry
manager classes class.
1.pack( ) method:It organizes the widgets in blocks before placing in the parent
widget.
2.grid( ) method:It organizes the widgets in grid (table-like structure) before placing
in the parent widget.
3.place( ) method:It organizes the widgets by placing them on specific positions dir
ected by the programmer.

Tkinter widgets
Tkinter provides various controls such as button,label and text boxes used in a GUI
applications.These controls are commonly called Widgets.There are several types of
widgets in Tkinter.
Some of the major widgets are explained below:

Sr.No. Operator & Description

1 ButtonThe Button widget is used to display buttons in your application.

2 CanvasThe Canvas widget is used to draw shapes, such as lines, ovals,


polygons and rectangles, in your application.

3 CheckbuttonThe Checkbutton widget is used to display a number of options


as checkboxes. The user can select multiple options at a time.

4 EntryThe Entry widget is used to display a single-line text field for accepting
values from a user.

5 FrameThe Frame widget is used as a container widget to organize other


widgets.

6 LabelThe Label widget is used to provide a single-line caption for other


widgets. It can also contain images.
7 ListboxThe Listbox widget is used to provide a list of options to a user.

8 MenubuttonThe Menubutton widget is used to display menus in your


application.

9 MenuThe Menu widget is used to provide various commands to a user.


These commands are contained inside Menubutton.

10 MessageThe Message widget is used to display multiline text fields for


accepting values from a user.

11 RadiobuttonThe Radiobutton widget is used to display a number of


options as radio buttons. The user can select only one option at a time.

12 ScrollbarThe Scrollbar widget is used to add scrolling capability to


various widgets, such as list boxes.

13 TextThe Text widget is used to display text in multiple lines.

14 tkMessageBoxThis module is used to display message boxes in your


applications.

Label Widget
A Label is a tkinter widget class.It refers to the display box where you can put any
text or image .The label is widget that the user just views but not interacts with.The
text displayed by this widget can be updated at any time we want.
The general syntax is:
w=Label(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of them
are listed below.
1.anchor : It controls where the text is positioned if the widget has more space than
the text needs.
2. bg: to set he normal background color displayed behind the label.
3.bd :Size of the border around the indicator.Default is 2 pixels.
4.cursor:set the mouse cursor pattern when it is over the text.
5.font: If we are displaying text in this label(using text or textvariable option), the
font option specifies in what font that text will be displayed.
6.text: To display one or more lines of text in a label widget, set this option to a
string containing the text.Internal newlines (“\n”)will force a line break.
7.textvariable:also used to set the text to be displayed.When the variable changes,
the text of the widget also changes.For this set this option to the StringVar().
from tkinter import *
top = Tk()
l1= Label(top, text="Hello World")
l1.pack()
top.mainloop()

Entry Widget
It is used to input the single line text entry from the user.It is the basic widget of
tkinter used to get input.For multi-line text input, Text widget is used.If the user
enters a string , which is longer than the available display space of the widget , the
content will be scrolled.This means that the string can not be seen in full.The arrow
key can be used to move to the invisible part of the string.The entry widget is also
limited to a single font.
The general syntax is:
w=Entry(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas.
Some of them are listed below.
1.bg: The normal background color displayed behind the label and the indicator.
2.bd:the size of the border around the indicator.Default is 2 pixels.
3.cursor: pattern of mouse cursor
4.font:The font used for the text.
5.show: Normally the characters that the user types appears in the entry.
To make a password entry that echoes each character as * , set show=“*”.
6.state:The default state is NORMAL.WE van use state=DISABLED to gray out the
control and make it unresponsive.
Eg:
from tkinter import *
root=Tk()
l1=Label(root,text="User Name")
l2=Label(root,text="Password")
E1=Entry(root)
E2=Entry(root)
l1.grid(row=0)
l2.grid(row=1)
E1.grid(row=0,column=1)
E2.grid(row=1,column=1)
root.mainloop()
OUTPUT

Methods used for Entry widget


1.get() :returns the entry’s current text as a string.
2.icursor(index):Set the insertion cursor just before the character at the given index.
3.select_clear():Clears the selection.If there isn’t currently a selection, has no effect.
4.select_present():If there is a selection, returns true, else returns false.
5. delete():Deletes characters from the widget.
6. insert ( index, ‘name’) Inserts string ‘name’ before the character at the given index.
Button widget
Button widget is used to add buttons in a Python applications.This button can be
used to 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:
b=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.
Sr.No. Option & Description

1 Activebackground: Background color when the button is under the cursor.

2 Activeforeground :Foreground color when the button is under the cursor.

3 Bd :Border width in pixels. Default is 2.

4 Bg :Normal background color.

5 Command: Function or method to be called when the button is clicked.

6 Fg:Normal foreground (text) color.

7 Font: Text font to be used for the button's label.

8 Height:Height of the button in text lines (for textual buttons) or pixels (for
images).

9 Image: Image to be displayed on the button (instead of text).

10 Justify: How to show multiple text lines: LEFT to left-justify each line; CENTER
to center them; or RIGHT to right-justify.

11 Padx:Additional padding left and right of the text.

12 Pady:Additional padding above and below the text.

13 State: Set this option to DISABLED to gray out the button and make it
unresponsive. Has the value ACTIVE when the mouse is over it. Default is
NORMAL.
Methods

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

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

Eg:
from tkinter import *
top=Tk()
B=Button(top,text="submit")
B.pack()
top.mainloop()
OUTPUT

from tkinter import *


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

Message Widget
The Message widget is used to show the message to the user regarding the behavior
of the python application.The message text contains more than one line.Message
Widget is of non-editable type.
Syntax:
w = Message ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Eg:
from tkinter import *
root = Tk()
root.geometry("300x200")
msg = Message( root, text = "Hey!?How are you doing?")
msg.pack()
root.mainloop()
OUTPUT

Text Widget
Text Widget is used where a user wants to insert multiline text fields.This widget
can be used for a variety of applications where the multiline text is required such as
messaging, sending information or displaying information and many other tasks.
Syntax
T = Text(master,option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Options are:
bg – background colour
fg – foreground colour
bd – border of widget.
height – height of the widget.
width – width of the widget.
font – Font type of the text.
cursor – The type of the cursor to be used.
state – defines if the widget will be responsive to mouse or keyboards movements.
yscrollcommand – to make the widget vertically scrollable.
xscrollcommand – to make the widget horizontally scrollable.
Text Widget Methods

Methods for Tag Handling


Mainly tags are used to configure different areas of the text widget separately. Tag
is basically
the name given to separate areas of the text. Some Methods for handling tags are
given below
1.tag_add(tagname, startindex, endindex)
– This method is mainly used to tag the string that is present at the specifiedindex.
2.tag_delete(tagname)
– This method is mainly used to delete the specified tag.
3.tag_remove(tagname, startindex, endindex)
– To remove the tag from the specified range this method is used
Methods for Mark Handling
In a given text widget in order to bookmark specified positions between the
characters Mark is
used. Some methods for the same are given below:
1.index(mark)
– This method is mainly used to get the index of the mark specified.
2.mark_names()
– This method is used to get all the names of the mark in the range in the text
widget.
3.mark_set(mark, index)
– This method is used to inform the new position of the given mark.
4.mark_unset(mark)
– In order to remove the given mark from the text this method will be used.
Eg:
from tkinter import *
root=Tk()
t=Text(root,height=2,width=30)
t.pack()
t.insert(END,"Python Programming \n Let's try \n")
root.mainloop()
OUTPUT
Ckeckbutton Widget
It displays a number of options to the user , and permit the user to make multiple
selections from the available options.This is different to radio button , where the user
can make only one choice.Usually check buttons are shows on the screen as square
boxes.The state of the check button is changed by clicking the mouse on the button.
It has two states:On and OFF.
Syntax:
w = Checkbutton ( master, option, ... )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Checkbutton Widget Methods:
Eg:
from tkinter import *
root=Tk()
l1=Label(root,text="Qualification")
c1=Checkbutton(root,text="SSLC",onvalue=0,offvalue=1)
c2=Checkbutton(root,text="PLUS TWO",onvalue=0,offvalue=1)
c3=Checkbutton(root,text="DEGREE",onvalue=0,offvalue=1)
l1.pack(anchor=W)
c1.pack(anchor=W)
c2.pack(anchor=W)
c3.pack(anchor=W)
root.mainloop()
OUTPUT

Radiobutton Widget
Radiobutton allows the user to choose exactly one option from the set of given
options.It may contain text or image.Also, different methods can also be associated
with radiobutton.
Syntax
W = Radiobutton(master, options)
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Options are same as CheckButton
* value=When a radio button is turned on by the user , its control variable is set to
its current value option.
Methods are same as CheckButton
Eg:
from tkinter import *
root=Tk()
l1=Label(root,text="Gender",)
r1=Radiobutton(root,text="Male",value=1)
r2=Radiobutton(root,text="Female",value=2)
r3=Radiobutton(root,text="Transgender",value=3)
l1.pack(anchor=W)
r1.pack(anchor=W)
r2.pack(anchor=W)
r3.pack(anchor=W)
root.mainloop()
OUTPUT
Listbox Widget
The Listbox widget is used to display a list of items from which a user can select a
number of items.It can only contain text items and all items must have the same font
and color.Depending on how the listbox is configured , the user can select one or
many items from the list.
Syntax
w = Listbox ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
When we first create the listbox, it is empty.We usually insert one or more items to
the list. The insert() method takes an index and a string to insert.Index is an item
number begins from 0.
Option:
bd :This option is used to represent the border width of the widget.
bg :background colour
fg :foreground colour
width :width of the widget.
height :height of the widget.
font :Font type of the text.
cursor :The cursor on the widget which can be an arrow, a dot etc
xscrollcommand : If you want to allow the user to scroll the listbox horizontally,
you can link your listbox widget to a horizontal scrollbar.
yscrollcommand : If you want to allow the user to scroll the listbox vertically,
you can link your listbox widget to a vertical scrollbar.
selectmode :Determines how many items can be selected, and how mouse
drags affects the selection.
* BROWSE: Default value.You can only select one item from the listbox.
If you click on an item and then drag to a different line , the
selection will follow the mouse.
*SINGLE: You can only select one item, and you can’t drag the mouse.
*MULTIPLE: You can select any number of items at once.
*EXTENDED: You can select any adjacent group of lines at once by clicking
on the first line and dragging to the last line.

Methods used in listbox widgets are as follows:


xview() : allows the widget to be vertically scrollable.
yview() : allows the widget to be horizontally scrollable.
get() : to get the list items in a given range.
activate(index) : to select the lines with a specified index.
size() : return the number of lines present.
delete(start, last) : delete lines in the specified range.
nearest(y) : returns the index of the nearest line.
curselection(): Returns a tuple containing the line numbers of the
selected element or elements, counting from 0
Eg1:
from tkinter import *
root=Tk()
list=Listbox(root,height = 10,width = 15,bg = "grey",fg = "yellow")
list.pack()
for item in ["APPLE","ORANGE","GRAPES","BANANA"]:
list.insert(END,item)
root.mainloop()
OUTPUT

Eg2:
from tkinter import *
root=Tk()
list=Listbox(root,height = 10,width = 15,bg = "grey",fg = "yellow")
root.geometry("300x250")
label=Label(root,text=" FOOD ITEMS")
list.insert(1, "Nachos")
list.insert(2, "Sandwich")
list.insert(3, "Burger")
list.insert(4, "Pizza")
list.insert(5, "Burrito")
label.pack()
list.pack()
root.mainloop()
OUTPUT

Scrollbar Widget
The scrollbar widget is used to implement vertical scrolled widgets that is scroll
down the content.
We can also create the horizontal scrollbars to the Entry widget.
Syntax
w = Scrollbar ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget
Options are:
activebackground :The color of the slider and arrowheads when the mouse is over
them.
bd: This option is used to represent the border width of the widget.
bg: The color of the slider and arrowheads when the mouse is not over them.
cursor: In this option, the mouse pointer is changed to the cursor type,set to this
option which can be an arrow, dot, etc
width: Width of the scrollbar (its y dimension if horizontal, and its x dimension if
vertical).Default is 16.
orient: This option can be set to HORIZONTAL or VERTICAL depending upon the
orientation of the scrollbar.
jump: This option is used to control the behavior of the scroll jump. If it set to 1,
then the callback is called when the user releases the mouse button.
Methods used in this widgets are as follows:
1.get():This method is used to returns the two numbers a and b
which represents the current position of the scrollbar.
2.set ( first, last ) :To connect a scrollbar to another widget w, set w’s
xscrollcommand or yscrollcommand to the scrollbar’s set() method.
The arguments have the same meaning as the values returned by the
get() method.
Eg:
from tkinter import *
root = Tk()
root.geometry("300x250")
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )
mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert(END, "This is line number " + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()
OUTPUT

Spinbox widget
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
Syntax
w = Spinbox ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Eg:
from Tkinter import *
master = Tk()
w = Spinbox(master, from_=0, to=10)
w.pack()
mainloop()

OUTPUT
Menu widget
Menus are the important part of any GUI.It allows us to create all kinds of menus
that can be used by our applications.
Syntax
w = Menu ( master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Eg:
from tkinter import *
root = Tk()
root.title('Menu Demonstration')
# Creating Menubar
menubar = Menu(root)
# Adding File Menu and commands
file = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='File', menu = file)
file.add_command(label ='New File', command = None)
file.add_command(label ='Open...', command = None)
file.add_command(label ='Save', command = None)
# Adding Edit Menu and commands
edit = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Edit', menu = edit)
edit.add_command(label ='Cut', command = None)
edit.add_command(label ='Copy', command = None)
edit.add_command(label ='Paste', command = None)
edit.add_separator()
edit.add_command(label ='Find...', command = None)
edit.add_command(label ='Find again', command = None)
# display Menu
root.config(menu = menubar)
mainloop()
OUTPUT

Menubutton widget
A Menubutton is a part of a drop-down menu that stays on the screen all the time.
Every Menubutton is associates with a Menu widget that can display the choices for
that menu button when user clicks on it.
Syntax:
m=Menubutton(master, option )
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Options are:
1.activebackground: The back ground color when the mouse is over the menu button.
2.activeforeground: The foreground color when the mouse is over the menu button.
3.anchor : same as other widget
4.bg : Normal background color behind the label and indicator.
5.bd : size of border.
6.cursor : same as other widget.
7.relief : Selects three- dimensional border shading effects.
8.state : Set state=DISABLED , to gray out the menu button and make it
unresponsive.
Eg:
from tkinter import *
root = Tk()
root.geometry("300x200")
l = Label(root, text ='CONCORD', font = "50")
l.pack()
menubutton = Menubutton(root, text = "Menu")
menubutton.menu = Menu(menubutton)
menubutton["menu"]= menubutton.menu
menubutton.menu.add_checkbutton(label = "Courses")
menubutton.menu.add_checkbutton(label = "Students")
menubutton.menu.add_checkbutton(label = "Careers")
menubutton.pack()
root.mainloop()
OUTPUT

Scale widget ( Slider widget )


The Scale widget is used to implement the graphical slider to the python application
so that the user can slide through the range of values shown on the slider and select
the one among them.
We can control the minimum and maximum values along with the resolution of the
scale. It provides an alternative to the Entry widget when the user is forced to select
only one value from the given range of values.
The syntax to use the Scale widget is given below.
Syntax
w = Scale(master, options)
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
1 Activebackground The background color of the widget when it has the focus.

2 Bg The background color of the widget.

3 Bd The border size of the widget. The default is 2 pixel.

4 Command It is set to the procedure which is called each time when we move
the slider. If the slider is moved rapidly, the callback is done
when it settles.
5 Cursor The mouse pointer is changed to the cursor type assigned to this
option. It can be an arrow, dot, etc.

6 Digits If the control variable used to control the scale data is of string
type, this option is used to specify the number of digits when the
numeric scale is converted to a string.

7 Tickinterval The scale values are displayed on the multiple of the specified
tick interval. The default value of the tickinterval is 0.

8 from_ It is used to represent one end of the widget range.

9 To It represents a float or integer value that specifies the other end


of the range represented by the scale.

10 Label This can be set to some text which can be shown as a label with
the scale. It is shown in the top left corner if the scale is
horizontal or the top right corner if the scale is vertical.

Methods

SN Method Description

1 get() It is used to get the current value of the scale.

2 set(value) It is used to set the value of the scale.

Eg:
from tkinter import *
top=Tk()
top.geometry("200x200")
s=Scale(top,from_=0,to=20,tickinterval=4)
s.set(10)
s.pack()
top.mainloop()
OUTPUT

Frames
The Frame widget is for grouping and organizing other widgets.It works like
a container , which is responsible for arranging the position of other widgets.It uses
a rectangular area on the screen to organize the layout and to provide padding of
these widgets.A Frame can also be used as a foundation class to implement complex
widgets.If you make a GUI app, you’ll be using different widgets, Those widgets
need to be organized somehow, that’s where a frame comes in.
Syntax:
f=Frame(master,options)

Options:
bg: Background color
bd:Size of border around it.
cursor:Style of mouse cursor.
height:Vertical dimension of the new frame.
width:Horizontal dimension of the new frame.
Eg:
from tkinter import *
root=Tk()
root.geometry("200x200")
frame=Frame(root)
frame.pack()
bottomframe=Frame(root)
bottomframe.pack(side=BOTTOM)
redbutton=Button(frame,text="APPLE",fg="red")
redbutton.pack(side=LEFT)
greenbutton=Button(frame,text="PEAR",fg="green")
greenbutton.pack(side=LEFT)
bluebutton=Button(frame,text="GRAPES",fg="blue")
bluebutton.pack(side=LEFT)
blackbutton=Button(bottomframe,text="BLACKBERRY",fg="black")
blackbutton.pack(side=BOTTOM)
root.mainloop()
OUTPUT
Canvas Widget
The Canvas widget supplies graphics facilities for tkinter.Among these graphical
objects are lines, circles , images etc.With this widget it is possible to draw graphs
and plots.
Syntax:
c=Canvas(master,option)
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Optional parameters:
• root = root window.
• height = height of the canvas widget.
• width = width of the canvas widget.
• bg = background colour for canvas.
• bd = border of the canvas window.
• scrollregion (w, n, e, s)tuple defined as a region for scrolling left, top, bottom
and right.
• highlightcolor colour shown in the focus highlight.
• cursor It can be defined as a cursor for the canvas which can be a circle, a do,
an arrow etc.
• confine decides if canvas can be accessed outside the scroll region.
• relief type of the border which can be SUNKEN, RAISED, GROOVE and
RIDGE.

Methods used for drawing on Canvas are:


1.create_line() ------ Create a line
line = C.create_line(x0, y0, x1, y1, options)
2.create_polygon ------ Create a polygon
polygon=C.create_polygon(x0, y0, x1, y1, ...xn, yn, options)
3.create_oval() ------ Create a circle / ellipse / oval
oval = C.create_oval(x0, y0, x1, y1, options)
4.create_arc() ------ Create an arc
arc=C.create_arc(coord,start=0,extend=120)
5.create_image() ------ Creates an image item
img=C.create_image(x0, y0,image=filename)
Eg:
from tkinter import *
top=Tk()
c=Canvas(top,height=300,width=300)
line=c.create_line(10,50,100,150)
polygon=c.create_polygon(170,120,120,200,200,170,fill="red")
oval=c.create_oval(220,250,150,200,fill="green")
arc = c.create_arc(20, 150, 80,210, start=0,extent=220,fill="yellow")
c.pack()
top.mainloop()
OUTPUT
Eg:
from tkinter import *
top=Tk()
c=Canvas(top,bg="blue",height=600,width=600)
filename=PhotoImage(file="pic.png")
img=c.create_image(200,150,image=filename)
c.pack()
top.mainloop()
OUTPUT

LAYOUT MANAGERS / GEOMETRY MANAGERS


Layout managers are also known as geometry managers.
Tkinter have three geometry managers:
1.Pack
2.Grid
3.Place
They have several functions.
They arrange several widgets on the screen and manages the display of widgets on
the screen.Arranging widgets on the screen includes determining the size and
position of components.Widgets can provide size and alignment information to
geometry managers , but the geometry managers has always the final say on
positioning the sizing.
1.Pack Layout
Pack is the easiest to use of three geometry managers of tkinter.It determines where
a widget should be positioned and makes it visible when the main window is
displayed.Called for each widget in a window.Receives an argument to specify
positioning.Positioning depends on the order in which widgets were added to the
main window.
Valid arguments: side='top', side='left’, side='right’ .
Eg:
from tkinter import *
root =Tk()
l1 = Label(root, text="Red Sun", bg="red", fg="white")
l1.pack()
l2 = Label(root, text="Green Grass", bg="green",fg="black")
l2.pack()
l3 = Label(root, text="Blue Sky", bg="blue",fg="white")
l3.pack()
root.mainloop()
OUTPUT
Eg:
import tkinter as tk
root = tk.Tk()
w = tk.Label(root, text="red", bg="red", fg="white")
w.pack(padx=5, pady=10, side=tk.LEFT)
w = tk.Label(root, text="green", bg="green", fg="black")
w.pack(padx=5, pady=20, side=tk.LEFT)
w = tk.Label(root, text="blue", bg="blue", fg="white")
w.pack(padx=5, pady=20, side=tk.LEFT)
tk.mainloop()
OUTPUT

Eg:
import tkinter as tk
root = tk.Tk()
w = tk.Label(root, text="Red Sun", bg="red", fg="white")
w.pack(fill=tk.X, padx=10)
w = tk.Label(root, text="Green Grass", bg="green",fg="black")
w.pack(fill=tk.X, padx=10)
w = tk.Label(root, text="Blue Sky", bg="blue",fg="white")
w.pack(fill=tk.X, padx=10)
tk.mainloop()
OUTPUT

2.Grid Layout
The Grid geometry manager places the widget in a 2 – dimensional table,
which consist of a number of rows and columns.The position of a widget is defined
by a row and column numbers.Using the grid manager means that you create a
widget , and use the grid method to tell the manager in which row and column to
place them.The size of the grid does not have to be defined, because the manager
automatically determines the best dimensions for the widgets used.
Syntax:
widget.grid(row,column, other options)
Options:
1.row : The row to put the widget in.Default is the first row that is still empty.
2.column: The column to put widget in.Default 0 (leftmost column)
3.padx,pady : Shows how many pixels to pad widget, horizontally and vertically.
Eg:
from tkinter import *
root = Tk()
root.geometry("300x200")
l1=Label(root,text="RED",width=15)
l2=Label(root,text="GREEN",width=15)
l3=Label(root,text="BLUE",width=15)
b1=Button(root,bg="red",width=15)
b2=Button(root,bg="green",width=15)
b3=Button(root,bg="blue",width=15)
l1.grid(row=0,column=0)
b1.grid(row=0,column=1)
l2.grid(row=1,column=0)
b2.grid(row=1,column=1)
l3.grid(row=2,column=0)
b3.grid(row=2,column=1)
root.mainloop()
OUTPUT

3.Place Layout
The geometry manager allows us to explicitly set the position and size of a
window, either in absolute terms, or relative to another window.Place manager can
be accessed through the place method.It can be applied to all standard widgets.
Syntax:
widget.place(options)
Options:
1.anchor: The exact spot of widget other options refers to : may be
N,E,S,W,NE,NW,SE,SW. compass directions indicating the corners and sides of
widget: Default is NW ( the upper left corner of widget ).
2.bordermode: INSIDE ( the default ) to indicate that other options refers to the
parent’s inside ( ignoring the parent’s border) : OUTSIDE otherwise.
3.height,width : Height and Width in pixels.
4.x,y : Horizontal and Vertical offset in pixels.
Eg:
from tkinter import *
top=Tk()
top.geometry("300x300")
B1=Button(top,text="SUBMIT",bg="red")
B2=Button(top,text="CANCEL",bg="red")
B1.place(bordermode=OUTSIDE,height=100,width=100,x=10,y=50)
B2.place(bordermode=OUTSIDE,height=100,width=100,x=120,y=50)
top.mainloop()
OUTPUT

You might also like