0% found this document useful (0 votes)
41 views113 pages

Creating a Tkinter Root Window

The document provides an overview of creating graphical user interfaces (GUIs) using Tkinter in Python, focusing on the root window, fonts, colors, and containers like Frames and Canvases. It includes examples of creating buttons, handling events, and drawing shapes on a canvas. Key concepts such as widget creation, event handling, and layout management are also discussed.

Uploaded by

harekrishna28q
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)
41 views113 pages

Creating a Tkinter Root Window

The document provides an overview of creating graphical user interfaces (GUIs) using Tkinter in Python, focusing on the root window, fonts, colors, and containers like Frames and Canvases. It includes examples of creating buttons, handling events, and drawing shapes on a canvas. Key concepts such as widget creation, event handling, and layout management are also discussed.

Uploaded by

harekrishna28q
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

The Root Window

To display the graphical output, we need space on the screen. The


space that is initially allocated to every GUI program is called ‘top
level window’ or ‘root window’. We can say that the root window is
the highest level GUI component in any tinkter application. We can
reach the root window by creating an object of Tk class

Program 1: A python program to create root window or top level


window
Program 1 can be improved to display our own title in the root
window’s title bar. We can also set the size of the window to
something like 500 pixels X 400 pixels. It is also possible to replace
the TK’s leaf image with an icon of our choice. For this, we need to
use .ico file that contains an image.

Program 2: A python program to create root window with some


options
Fonts and Colours:
A font represents a type of displaying letters and numbers. In tkinter,
fonts are mentioned using a tuple that contains font family name,
size and font style as:
fnt = ('Times', -40, 'bold italic underline overstrike')
Here the font family name is ‘Times’ and font size is 40 pixels. If the
size is a positive number, it indicates the size in points. If the size is a
negative number, it indicates size in pixels. The style of the font can
be ‘bold’, ‘italic’, ‘underline’, ‘overstrike’. We can mention any one or
more styles as a string.

Program: 3 A python program to know available font families.


In tkinter, colors can be displayed in various ways using different
widgets like labels, buttons, frames, etc. Colors can be defined using:
Color Names: Predefined color names like 'red', 'blue', 'green', etc.
Hexadecimal Codes: Similar to HTML, you can specify colors using
hex codes like #RRGGBB, where RR, GG, and BB represent red, green,
and blue components.
RGB Format: Colors can also be set using RGB tuples, though they
need to be converted into a format tkinter understands.
Working with Containers
A container is a component that is used as a place where drwings or
widgets can be displayed. In short, a container is a space that displays
the output to the user. There are two important containers:
Canvas: This is a container that is generally used to draw shapes like
lines, curves, arcs and circles.
Frame: This is a container that is generally used to display widgets
like buttons, check buttons or menus.

After creating 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.
Table 1: Basic Features and Layout

Feature Frame Canvas

Container widget for organizing other Widget for drawing shapes, displaying
Primary Purpose
widgets. images, and text.

Groups and organizes other widgets (e.g., Allows drawing shapes, images, text, and
Functionality
buttons, labels). custom objects at specific coordinates.

Does not use layout managers for items


Supports pack(), grid(), and place() to
Layout Management inside it; uses coordinates (x, y) for
organize child widgets.
placement.

Supports scrolling with built-in scroll region


Does not inherently support scrolling.
Scrollable and scrollbars. Ideal for large drawings or
Scrollbars must be added manually.
zoomable content.

Can contain graphical objects but not


Can be nested inside other widgets,
Nesting widgets (widgets can only be placed using
including other Frames.
external Frames).

Relies on layout managers for positioning Provides fine-grained control over


Precision Placement
widgets. positioning through exact coordinates.

Supports borders with styles like SUNKEN, Typically no border (though it can be added
Border Styles
RAISED, GROOVE, etc. manually if needed).
Table 2: Use Cases, Contents, and Performance
Feature Frame Canvas

Creating drawings, graphs,


Organizing forms, buttons, input fields,
Use Case visualizations, and games. Also useful
and sections of a window.
for custom widget creation.

Cannot hold standard Tkinter widgets


Primarily for grouping and laying out
Handling Widgets directly (only graphical elements like
widgets.
shapes and images).

Supports rich event handling (e.g.,


Supports event handling, but limited in
Event Handling dragging, clicking) for graphical
graphical interactivity.
elements.

Drawing lines, shapes, and custom


Grouping input fields, labels, buttons; graphics; displaying images; creating
Common Use Cases
dividing the window into sections. interactive elements like draggable
objects.

Handles more complex graphical


Performance Lightweight; doesn’t render graphics. operations; may become slower with
many objects.

Other Tkinter widgets like Button, Drawings, images, text, lines, polygons,
Typical Contents
Label, Entry. etc.

Grouping form elements in a dialog Drawing an interactive map or diagram


Example
box. with shapes and images.
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=‘cross’)
Here, ‘c’ is the Canvas class object . ‘root’ is the name of the parent
window. ‘bg’ represents the background colour, ‘height’ and ‘width’
of 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.
Once the canvas is created , it should be added to the root window.
Then it will be visible. This is done using pack method.
[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
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
To create a oval,
This creates an oval in the rectangular area defined by the top left
coordinates (100,100) and bottom lower coordinates (400,300). If the
rectangle has same width and height, then the oval will become
circle. ‘width’ represents the width of the oval in pixels. ‘fill’
represents the colour to fill and outline represents the colour to be
used for border. The option ‘active fill’ represents the colour to be
filled when the mouse is placed on the oval.
To create a polygon
Here the polygon is created using the points (10,10), (200,200),
(300,200) and then the last point is again connected to the first point
i.e. (10,10). The option ’smooth’ can become 0 or 1 . If 0, it indicates a
polygon with sharp edges and 1 indicates a polygon with smooth
edges
To create a rectangle
Here the rectangle will be formed with the top left coordinates at
(100,200) pixels and the lower bottom coordinates at (400,400).
To display text
It is also possible to display some text in the canvas. For this purpose,
we should use the create_text() method as:
id=c.create_text(400,100, text =“My canvas”, font=fnt, fill=“yellow”,
activefill=“green”)
The [Link] method is used to define a custom font. You can
specify the font family, size, and style (e.g., bold, italic).
To write a GUI program that displays various shapes
To write a GUI program that displays various shapes
Another important shape that we can draw in the canvas is an arc. An
arc represents a part of an ellipse or circle. Arcs can be created using
the create_arc() method as:
Id=c.create_arc(100, 100, 400, 300, width=3, start=270, extent =180,
otline=“red”, style =“arc”)
Here the arc is created in the rectangular space defined by the
coordinates (100,100) and (400,300). The width of the arc will be 3
pixels. The arc will start at an angle 270 degrees and extend for
another 180 degrees (i.e. up to 450 degrees means 450-360=90. The
outline of the arc will be in red color. ‘style’ option can be ‘arc’ for
drawing arcs. ‘style can be “pie slice” and “chord”.
As mentioned, the option ‘start’ represents an angle of the arc where
it has to start and ‘extent’ represents the angle further which the arc
should extend. These angles should be taken in the counter clockwise
direction, taking the 3 O’ clock position as 0 degrees. Thus the 12 O’
clock position will show 90 degrees , the 9 O’ clock will be 180
degrees and the 6 O’ clock will represent 270 degrees
Key Points:
Image Loading:
Make sure the image file (IMG_20160626_151704.jpg) is in the correct path. If it's not,
you'll get an error.
Use the full path to the image or ensure it's in the same directory as your Python script.
Image Persistence:
In Tkinter, images can sometimes be garbage-collected prematurely. To prevent this,
store a reference to the image using a global variable or attaching it to a widget.
Image Positioning:
The create_image() method's position (500, 400) refers to the center of the image. You
may need to adjust this based on your image size.
Canvas Dimensions:
The canvas size (1200x700) might need adjustment to fit the image properly.
Frame
In Tkinter, a Frame is a widget used as a container to organize and group other widgets
within a window. It's particularly useful for organizing layouts in a structured way, dividing a
window into sections, and managing the positioning of multiple widgets (like labels, buttons,
text boxes, etc.).
Widget
A widget is a GUI component that is displayed on the screen and can perform a task as
desired by the user. We create widgets as objects. For example, a push button is a widget
that is nothing but an object of button class. Similarly, label is a widget that is an object of
label class. Once a widget is created, it should be added to canvas or frame. The following
are important widgets in Python:
 Button
 Label
 Message
 Text
 Scrollbar
 Checkbutton
 Radiobutton
 Entry
 Spinbox
 Listbox
 Menu
Widget
In general, working with widgets takes the following four steps:
1. Create the widgets that are needed in the program. A widget is a GUI components that is
represented as an objet of a class. For example, a push button is a widget that is
represented as Button class object
As an example, suppose we want to create a push button, we can create an object
to Button class as
Widget
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 Create the widgets that
are needed in the program. A widget is a GUI components that is represented as in
response to the events. Hence they are called ‘callback handlers’ or ‘event
handlers’. Other examples for events are pressing the Enter button, right clicking
the mouse button, etc.
As an example , let’s write a function may be called in response to button click.
Widget
3. When the user clicks on the push button, that ‘clicking’ event should be linked
with the ‘callback handler’ function. Then only the button widget will appear as if
it is performing some task.
As an example, let’s bind the button click with the function as
[Link](‘<Button-1>,buttonClick)
Widget
3. The previous three steps make the widgets ready for the user. Now the user
has to interact with the widgets. This is done by entering text from 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 ‘eventloop’.
As an example, we can use the mainloop() method that waits and processes the
event 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=‘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 background color of the button.
‘activebackground’ represents the background color when the button is clicked. Similarly,
‘activeforeground’ represents the foreground color when the button is clicked.

We can also display image on the button as:


# first load the image into file1
File1=PhotoImage(file=“[Link]”)
#create a push button with image
b= Button(f, image=file1, width=150, height =100, bg=‘yellow’, fg=‘blue’,
activebackground=‘green’, activeforeground=‘red’)
In the above statement, observe that the width and the height of the button are mentioned
in pixels.
Button Widget
In the previous program, we created a frame first and then created a push button with some
options and add a push button with some options and add the button to the frame. Then we
click the mouse left button with the buttonClick() method using bind() method as:
[Link](‘<Button-1>’,buttonClick)
Here ‘<Button-l>’ represents the mouse left button that is linked withbuttonClick() method.
It means when the mouse keft button is clicked, the buttonClick() method is called. This
method is called event handler.

In the place of ‘<Button-l>’, 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.
Button Widget
In the previous program, now we are going to make two changes:
First, we will eliminate bind() method and we will use ‘command’ option to link push button
with eventhandler function as
b= Button(f, text=‘My Button’, width=15, height =2, bg=‘yellow’, fg=‘blue’,
activebackground=‘green’, activeforeground=‘red’, Command=buttonClick)

Secondly, we will rewrite the same program using class concept where the entire code
will be written inside the class.
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 bys passing some argument that represents which button is
clicked. For example:
b1=Button(f, text=‘Red’, width =15, height=2, command=lambda: buttonClick(1))
Here, we are creating a push button ‘b1’. Pleas observe the ‘command’ option. Here, we are
using the ‘lambda’ expression to pass the argument 1 to the buttonClick() method, in the
following format:
command=lambda: buttonClick(arg1,arg2,…….)
Usually, ‘command’ option allows to mention the method name only and it is not possible to
pass arguments to the method. Suppose we want to pass arguments, then we need to use
lambda expression as mentioned in the expression.
In the next program, we are creating 3 push buttons by the names ‘Red’, ‘Green’ and ‘Blue’.
When the user clicks a button we will change the back ground color of the frame according
to the button clicked. This is possible by passing an integer 1,2 or 3 to the event handler
method to indicate which button is clicked. This integer is stored in a variable ‘num’ at the
method.
When the button is clicked, we are changing the background color of the frame as:
def buttonClick(self, num):
If num==1:
Self.f*“bg”+=‘red’
If num==2:
Self.f*“bg”+=‘green’
Here, observe that the ‘bg’ is the option of the frame ‘f’. To set the back ground color of the
frame, we can write:
self.f*“bg”+=‘red’# set new color for bg
In the same way, we can set other options for the frame as:
self.f*“height”+=500# set new height
self.f*“width”+=600# set new height
Arranging Widgets in the Frame
Once we create widgets or components, we can arrange them in the frame in a particular
manner. Arranging the widgets in the frame is called ‘layout management’. There are three
types of layout managers:
 Pack layout manager
 Grid layout manager
 Place layout manager

Pack layout manager uses pack() method. This method is useful to associate a widget with its
parent component. While using the pack() method, we can mention the position of the widget
using ‘fill’ or ‘side’ options.
[Link](fill=X)
[Link](fill=Y)
The ‘fill’ option can take the values: X,Y, BOTH, NONE. The value X represents that the widget
should occupy the frame horizontally and the value Y represents that the widget should occupy
vertically. BOTH represents that the widget should occupy in both the directions. NONE
represents that the widget should be displayed as it is. The default value is NONE. Along with
‘fill’ option, we can use ‘padx’ and ‘pady’ options that represent how much space should be left
around the component horizontally and vertically. For example,
[Link](fill=Y, padx=10, pady=15)#occupy vertically. Space on x-axis 10 px, on y-axis 15 px
[Link](fill=X, padx=10, pady=15)#occupy horizontally. Space on x-axis 10 px, on y-axis 15 px
[Link](fill=X)#occupy horizontally. No space outside widget
[Link](fill=Y)#occupy vertically. No space outside widget
Arranging Widgets in the Frame
The Pack() method can take another option ‘side’ which is used to place the widgets side by
side. ‘side’ can take the values LEFT, RIGHT, TOP or BOTTOM. The default value is TOP. For
example,
[Link](side=LEFT, padx=10, pady=15)#align towards left with 10 px and 15 px spaces
[Link](side=LEFT, padx=10, pady=15)#align towards left with 10 px and 15 px spaces
[Link](side=RIGHT)#align towards right with 0 px space around the widget
[Link]()#align towards top with 0 px space around the widget
Arranging Widgets in the Frame
Grid layout manager uses the grid() method to arrange the widgets in a two dimensional table
that contains rows and columns. We know that the horizontal arrangement of data is called
‘row’ and vertical arrangement is called ‘column’. The position of a widget is defined by a row
and a column number. The size of the table is determined by the grid layout manager
depending on the widgets size.
[Link](row=0, column=0, padx=10, pady=15)#display in 0th row,0th column with spaces around
[Link](row=0, column=1, padx=10, pady=15)#display in 0th row,1st column with spaces around
[Link](row=0, column=2)#display in 0th row, 2nd column without spaces
[Link](row=1, column=3)#display in 0th row, 2nd column without spaces
Arranging Widgets in the Frame
Place layout manager uses the place() method to arrange the widgets. The place() method takes
x and y coordinates of the widget along with width and height of the window where the widget
has to be displayed. For example,

[Link](x=20, y=30, width=100, height =50)#display at (20,30) coordinates in the window 100 px width
and 50 px height
[Link](x=20, y=100, width=100, height =50 )#display at (20,100)
[Link](x=200, y=100, width=100, height =50 )#display at (200,100)
[Link](x=200, y=200, width=100, height =50 )#display at (200,200)
Label Widget
A label represents constant text that is displayed in the frame or container. A label can display
one or more lines of text that cannot be modified. A label is created as an object of Label class
as:
lb1=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 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.

Here when the code is executed with ‘quit’, it closes the Tkinter event loop but doesn't always
properly terminate the entire application. A better approach is to use [Link]() or
[Link]() for closing the application window cleanly.
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’, bg=‘yellow’)
Text Widget
Text widget is same as a label or message. But Text widget has several options and can display
multiple lines of text in different colors and fonts. It is possible to insert text into a Text widget,
modify it or delete it. We can also display images in the Text widget. One can create a Text
widget by creating an object to Text class as:
t=Text(root, width = 20, height = 10, font=(‘Verdana’, 14, ‘bold’), fg=‘blue’, bg=‘yellow’,
wrap=WORD)
Here ‘t’ represents the object of Text class. ‘root’ represents an object of root window or frame.
‘width’ represents the width of the Text widget in characters. ‘height’ represents the height of
widget in lines. The option ‘wrap’ specifies where to cut the line. Wrap=CHAR represents that
any line that is too long will be broken at any chatacter. 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 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.
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 the
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 roo 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’))
Here, we are applying ‘red’ background and ‘white’ foreground and ‘Lucida console’ font to the
text that is already named as ‘start’ tag. In this way, we can have several tags in Text widget.

In many cases, it is useful to add scroll bars to the Text widget. 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 vertical scroll bar or horizontal scroll bar. The ‘command’
option specifies to which widget this scroll bar should be connected. ‘[Link]’ represents that
the scrollbar is connected to ‘t’, i.e. Text widget and ‘yview’ is for vertical scrolling.
[Link](yscrollcommand=[Link])
We should set the ‘yscrollcommand’ option of the text widget ‘t’ to ‘[Link]’ method. In this way,
the scroll bar ‘s’ is connected to Text widget ‘t’.
Scroll bar
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 list box 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 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])
Here, ‘h’ represents the Scrollbar object which is created as a child to ‘root window’. The option
‘orient’ indicates HORIZONTAL for horizontal scroll bars and VERTICAL indicates vertical scroll
bars. ‘bg’ represents back ground color for the scroll bar. This option may not work in Windows
since Window operating system may force some default background color for the scroll bar
which will not be disturbed by the tkinter. The option ‘command’ represents the method that is
to be executed. The method ‘xview’ is executed on the object ‘t’. Here, ‘t’ may represent a
widget like Text widget or Listbox.
Similarly, to create a vertical scroll bar ‘v’, we can write:
v=Scrollbar(root, orient=VERTICAL, bg=‘green’, command=[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 bars as:
[Link](xscrollcommand=[Link])
Finally, the scroll bar should be attached to the root window using the pack() or grid() method
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 statement:
[Link](side=RIGHT, fill=Y)
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)
Here, ‘c1’ is the object of Checkbutton class the represents a check button. ‘f’ indicates frame
for which the check button becomes a child. ‘bg’ and ‘fg’ represent the back ground and fore
ground colors used for check button. ‘font’ represents the font name, size and style. ‘text’
represents the text to be displayed after the check button. The option ‘variable’ represents an
object of IntVar() class. ‘command’ represents the method to be called when the user clicks the
check button.
The class ‘IntVar’ is useful to know the state of the check button, whether it is clicked or not.
The IntVar class object can be created as:
var1=Intvar()
When the check button is clicked or selected, the value of ‘var1 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

Program16: Write a python program to create 3 check buttons and know which options are
selected by the user.
Radiobutton Widget
A radio button is similar to a check button, but it is useful to select only one option fro 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)
Here, ‘r1’ is the object of Radiobutton class the represents a radio button. ‘f’ indicates frame for
which the check button becomes a child. ‘bg’ and ‘fg’ represent the back ground and fore
ground colors used for check button. ‘font’ represents the font name, size and style. ‘text’
represents the text to be displayed after the check button. The option ‘variable’ represents an
object of IntVar() class. ‘value’ represents a value that is set to this object when the radio button
is clicked. ‘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:
var = Intvar()
When the user clicks the radio buttonton is clicked or selected, 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 button ‘r1’ is clicked
by the user. In this way, it is possible to know which button is clicked by the user.

Program 17: Write a python program to create radio buttons and know which button is
selected 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. For example, we can display names, passwords or credit card numbers using entry widgets.
An Entry widget can be created as an object of Entry class as:
e1=Entry(f, width=25, bg=‘yellow’, fg=‘green’, font=(‘Arial’, 14), show=‘*’)
Here, ‘e1’ is the Entry class object. ‘f’ indicates the frame which is the parent component for the
Entry widget. ‘width’ represents the size of the widget in number of characters. ‘fg’ indicates
the foreground color in which the text in the widget is displayed. ‘bg’ represents the
background color in the widget. ‘font’ represents a tuple that contains font family name, size
and style. ‘show’ represents a charcater that replaces the originally typed characters in the
Entry widget. For example, show=‘*’ is useful when the user wants to hide his password by
displaying stars in the placeof characters.
After typing text in the Entry widget, the user presses Enter (or Return) button. Such an event
should be linked with the entry widget using bind() method as:
[Link](“<Return>”. [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):
As seen in the preceding code, we are catching the event through an argument ‘event’ in the
display() method. The argument is never used inside the method. The method consists of the
code that is to be executed when the user pressed Enter button.
Program 18: Write a python program to create Entry widgets for entering user name and
password and display the entered text.
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 on Entry
widget.
A spinbox 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’))
Here, ‘f’ represents the parent widget. ‘from_’ indicates the starting value and ‘to’ indicates the
ending value in the spin box. ‘textvariable’ shows the control variable, i.e. ‘vaa1’ that is created
as an object of the IntVar class, as follows:
val1=Intvar()
‘val1’ is control variable that receives the displayed value in the spin box. Similarly, we can
create a spin box with strings by specifying the strings as a tuple as shown in the following
statement:
s2=Spinbox(f, values=(‘Hyderabad’, ‘New_Delhi’, ‘Kolkata’, ‘Banglore’), textvariable=val2,
width=15, fg=‘black’, bg=‘green’, font=(‘Arial’,14, ‘bold italic’))
Here, the fixed strings that are displayed in the spin box are mentioned in the ‘values’ option as
tuple as shown in the following statement:
values==(‘Hyderabad’, ‘New_Delhi’, ‘Kolkata’, ‘Banglore’)
The ‘textvariable’ option indicates the control variable ‘val2’ that is created as an object of
StringVar class as shown in the following statement:
Val2=StringVar()

‘val2’ contains the displayed string in the spin box. To retrieve the values from the control
variables, we can use the get() method as:
a=[Link]()#get the number from val1
s=[Link]()#get the number from val2
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(self.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 line shown in the
list box. ‘width’ represents the width of the list box in terms of numbers of characters and the
default is 20 characters. The option ‘activestyle’ indicates the appearance of the selected item.
It may be ‘underline’, ‘dotbox’ or ‘none’. The default value is ‘underline’. The option
‘selectmode’ may take any of the following values:
BROWSE: Normally, we can select one item (or line) out of a list box. If we click on an item and
then drag to a different item, the selection will follow the mouse. This is the default value of
‘selectmode’ option.
SINGLE: This represents that we can select only one item (or line) from all available list of items.
MULTIPLE: We can select 1 or more number of items at once by clicking on the items. If an item
is already selected, clicking second time on the item will un-select it
EXTENDED: We can select any adjacent group of items at once by clicking on the first item and
dragging to the last item.

Once the list box is created, we should insert items into the list box using insert() method as:
[Link](0, ‘Stanford University’)
[Link](1, ‘Oxford University’)
Listbox Widget
To bind the Listbox Select event with a method, we can use the bind() method as:
[Link](‘<<Listboxselect>>’,on_select)
The meaning of the previous statement is that when the user selects any items in the list box.
The method on_select() will be called. This method can be written something like this:
def on_select(event):
#create an empty list box
lst=[]
#know the indexex of the selected items
Indexes=[Link]()
#retrieve the items names depending on indexes
#append the items names to the list box
for i in indexes:
[Link]([Link](i))
Observe the on_select() method. It has a parameter ‘event’ that is useful to catch the
ListboxSelect event. We need not to do anything with this event inside the method. To retrieve
the indexes or position numbers of the selected items, we can use curseselection() method of
Listbox class. Suppose, we want to know the names of the items based on the indexes, we can
use get() method of the Listbox class. In the on_select() method, we are appending the names
of the selected items to a list box. Later the content of this list box can be displayed in a Text
box.
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
1. 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)
2. The menu bar should be attached to the root window using config() method as:
[Link](menu=menubar)
3. 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)
Here, ‘filemenu’ is the Menu class object. The option ‘tearoff’ can be 0 or 1. When this option is
1, the menu can be torn off. In this case, the first position (position 0) in the menu items is
occupied by the tear-off element which is a dashed line. If this option value is 0, then this
dashed line will not appear and the menu items are displayed starting from 0th position
onwards.
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)
Here, the menu item name is ‘New’ and when it is clicked by the user, the method donothing()
will be called. In this way, we can add any number of menu items to filemenu object. 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 a 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.
The output of this program will be exactly as shown in the previous slide. The output shows 2
menus attached to the menubar. The first one is the ‘File menu with 4 menu items: New, Open,
Save and Exit. Observe the horizontal line below the ‘Save’ option and above the ‘Exit’ option.
This horizontal line is called ‘separator’. The second menu attached to the menu bar is the ‘Edit’
menu which has 3 menu items: Cut, Copy and Paste. But none of these menu items will work ,
except the ‘Exit’ menu item. When the user clicks on FileExit item, the destroy() method is
called that destroys the root window and hence the root window will be closed. When the
other items like FileOpen is clicked, the donothing() method is called that does nothing.

Can’t we make the other menu items workable? Our intention is that when the user clicks on
FileOpen item, we want to display a file open dialog box where the user can select a file. Then
we read data from the file and display it in a Text widget. This can be done by writing a method
open_file(). In this method, first we should open a file dialog box for the user to select a file to
open as
filename=[Link](parent=root, title=‘Select a file’, filetypes=((“Python
files”, “*.py”),(“All files”, “*.*”)))
The ‘filedialog’ is a sub module in tkinter and hence it should be imported separately. In this
module we have ‘askopenfilename()’ method where we are supposed to specify which type of
files to open using ‘filetypes’ option in the following format:
filetypes==((“name”, “extension”), (“name”, “extension”))
Once the user selects a file in the dialog box, the file name is available to us in ‘filename’ object.
Now we can open this file and read its contents and display them in a Text box.
Similarly, we can make the FileSave item workable by writing a method save_file(). In this
method, we should first open a file dialog box for the user and ask him the filename on which to
save the data. This is done using ‘asksavefilename()’ method of filedialog module as:
filename=[Link](parent=root,defaultextension=“.txt”)
Here, the ‘defaultextension’ option specifies the default extension of files when we do not
mention any. Our assumption here is that the user has already has a file typed in the text box.
When the user specifies the file name, the typed data in the text box will be stored into the file
with the name specified by the user.
Creating Tables
A table is useful to display data in the form of rows and columns. Unfortunately, Python does
not provide a Table widget to create a table. But we can create a table using alternate methods.
For example, we can make a table by repeatedly displaying Entry widgets in the form of rows
and columns.
To create a table with 5 rows and 4 columns, we can use 2 for loops as:
for i in range(5):
for j in range(4):
Inside these loops, we have to create an Entry widget by creating an object of Entry class, as:
e=Entry(root, width=20, fg=‘blue’, font = (‘Arial’, 16, ‘bold’))
Now, we need logic to place this Entry widget in rows and columns. This can be done using
grid() method to which we can pass row and column positions, as:
[Link](row=i, column=j)#here i and j indicate row and column positions
We can insert data into Entry widget using insert() method, as:
[Link](END, data)
Here, ‘END’ indicates that the data continues to append at the end of the previous data in the
Entry widget.
This logic is used in the next program, to create a table using the data that is coming from a list.
We have taken a list containing 5 tuples and each tuple contain 4 values which indicate
employee ID, , name, city and salary. Hence we will have a table with 5 rows and 4 coumns in
each row. This program can be applied on the data coming from a database to display the entire
data in the form of a table.
Brief Tour of Other GUI Frameworks
While Tkinter is widely used, there are other GUI frameworks available for Python:
PyQt/PySide:
Both are Python bindings for the Qt toolkit.
They provide advanced features and a rich set of widgets.
Suitable for cross-platform applications.
wxPython:
A wrapper around the wxWidgets C++ library.
Provides native look and feel on different operating systems.
Supports a wide range of widgets and tools for building GUI applications.
Kivy:
An open-source Python library for developing multitouch applications.
Designed for mobile applications but can also be used for desktop apps.
Uses its own set of widgets and is highly customizable.
GTK+ (via PyGTK or PyGObject):
A multi-platform toolkit for creating graphical user interfaces.
Primarily used in Linux environments, but can also run on Windows and macOS.
Supports rich interfaces and modern UI designs.
Related Modules
Several Python modules can enhance GUI programming:
Pillow: A Python Imaging Library that allows for image processing and manipulation in GUI
applications.
matplotlib: Often used for plotting and graphing in GUI applications, it can embed plots in
Tkinter or other GUI frameworks.
PyOpenGL: A cross-platform Python binding to OpenGL, allowing for the creation of 3D graphics
in GUI applications.
SQLite3: For applications requiring a database, the built-in SQLite module can be used to
manage data.
.
GUI programming in Python offers a range of tools and frameworks to create interactive
applications. Tkinter is an excellent starting point for beginners, while other frameworks like
PyQt, wxPython, Kivy, and GTK provide more advanced features for professional applications.
Understanding the basics of widgets, event handling, and layout management is essential for
building effective GUI applications.

You might also like