Keith Tab W Tkinter Tutorial Learn Tkinter

Download as pdf or txt
Download as pdf or txt
You are on page 1of 241

TKINTER TUTORIAL

LEARN TKINTER
Tkinter is a standard library in python used for creating Graphical User
Interface (GUI) for Desktop Applications. With the help of Tkinter
developing desktop applications is not a tough task.
This tutorial will guide you to understand the working of the Tkinter module,
its various components like Windows, Widgets and Frames and will then
introduce you to all the available Tkinter widgets used for developing
desktop applications.
At the end of the tutorial we have few practical Tkinter projects for
beginners like Calculator App, Text Editor App and Music Player App.

-------------------------------------------------
TAB W. KEITH
Copyright © 2021 by Su TP. All Right Reserved.
TABLE OF CONTENTS
Introduction to Python Tkinter Module
Tkinter Windows, Widgets and Frames
Tkinter Windows
Python Tkinter Widgets
Python Tkinter Button Widget
Python Tkinter Canvas Widget
Python Tkinter Checkbutton Widget
Python Tkinter Frame Widget
Python Tkinter Label Widget
Python Tkinter Radiobutton Widget
Python Tkinter Text Widget
Python Tkinter Toplevel Widget
Python Tkinter Spinbox Widget
Python Tkinter PanedWindow Widget
Python Tkinter LabelFrame Widget
Python Tkinter MessageBox
Python Tkinter Scale Widget
Python Tkinter Scrollbar Widget
Python Tkinter Text Widget
Python Tkinter Toplevel Widget
Python Tkinter Spinbox Widget
Python Tkinter PanedWindow Widget
Python Tkinter LabelFrame Widget
Python Tkinter MessageBox
Python Tkinter Geometry Manager
Calculator Application using Tkinter
Text Editor Application Using Tkinter
Music Player Application using Tkinter
Introduction to Python Tkinter
Module
In this tutorial, we will cover an introduction to Tkinter, its prerequisites,
different ways for GUI Programming, how to install Tkinter, and its working.
Tkinter is a standard library in python used for creating Graphical User
Interface (GUI) for Desktop Applications. With the help of Tkinter
developing desktop applications is not a tough task.
The primary GUI toolkit we will be using is Tk , which is Python's default
GUI library. We'll access Tk from its Python interface called Tkinter (short
for Tk interface).

PREREQUISITES FOR TKINTER


Before learning Tkinter you should have basic knowledge of Python. You
can learn Python using our Complete Python Tutorial.

GUI PROGRAMMING IN PYTHON


There are many ways to develop GUI based programs in Python. These
different ways are given below:
Tkinter:
In Python, Tkinter is a standard GUI (graphical user interface)
package. Tkinter is Python's default GUI module and also the
most common way that is used for GUI programming in Python.
Note that Tkinter is a set of wrappers that implement the Tk
widgets as Python classes.
wxPython:
This is basically an open-source, cross-platform GUI toolkit that is
written in C++. Also an alternative to Tkinter.
JPython:
JPython is a Python platform for Java that is providing Python
scripts seamless access to Java class Libraries for the local
machine.
We will cover GUI Programming with Tkinter.

WHAT IS TKINTER?
Tkinter in Python helps in creating GUI Applications with a minimum
hassle. Among various GUI Frameworks, Tkinter is the only framework that
is built-in into Python's Standard Library.
An important feature in favor of Tkinter is that it is cross-platform, so
the same code can easily work on Windows, macOS, and Linux.
Tkinter is a lightweight module.
It is simple to use.

WHAT ARE TCL, TK, AND TKINTER?


Let's try to understand more about the Tkinter module by discussing more
about it origin.
As mentioned, Tkinter is Python's default GUI library, which is
nothing but a wrapper module on top of the Tk toolkit.
Tkinter is based upon the Tk toolkit, and which was originally designed
for the Tool Command Language (Tcl). As Tk is very popular thus it
has been ported to a variety of other scripting languages,
including Perl (Perl/Tk), Ruby (Ruby/Tk), and Python (Tkinter).
GUI development portability and flexibility of Tk makes it the right
tool which can be used to design and implement a wide variety of
commercial-quality GUI applications.
Python with Tkinter provides us a faster and efficient way in order to
build useful applications that would have taken much time if you had to
program directly in C/C++ with the help of native OS system libraries.
Once we have Tkinter up and running, we'll use basic building blocks
known as widgets to create a variety of desktop applications.

INSTALL TKINTER
Chances are, that Tkinter may be already installed on your system along with
Python. But it is not true always. So let's first check if it is available.
If you do not have Python installed on your system - Install Python 3.8 first,
and then check for Tkinter.
You can determine whether Tkinter is available for your Python interpreter
by attempting to import the Tkinter module - If Tkinter is available, then
there will be no errors, as demonstrated in the following code:
import tkinter
Nothing exploded, so we know we have Tkinter available. If you see any
error like module not found, etc, then your Python interpreter was not
compiled with Tkinter enabled, the module import fails and you might
need to recompile your Python interpreter to gain access to Tkinter.

ADDING TK TO YOUR APPLICATIONS

Basic steps of setting up a GUI application using Tkinter in Python are as


follows:
First of all, import the Tkinter module.
The second step is to create a top-level windowing object that contains
your entire GUI application.
Then in the third step, you need to set up all your GUI components and
their functionality.
Then you need to connect these GUI components to the underlying
application code.
Then just enter the main event loop using mainloop()
The above steps may sound gibberish right now. But just read them all, and
we will explain everything as we move on with this tutorial.

FIRST TKINTER EXAMPLE


As mentioned earlier that in GUI programming all main widgets are only
built on the top-level window object.
The top-level window object is created by the Tk class in Tkinter .
Let us create a top-level window:
import tkinter as tk
win = tk.Tk()
###you can add widgets here
win.mainloop()

TKINTER METHODS USED ABOVE:


The two main methods are used while creating the Python
application with GUI. You must need to remember them and these are given
below:
1. Tk(screenName=None, baseName=None, className='Tk', useTk=1)
This method is mainly used to create the main window. You can also
change the name of the window if you want, just by changing
the className to the desired one.
The code used to create the main window of the application is and we have
also used it in our above example:
win = tkinter.Tk() ## where win indicates name of the main window object
2. The mainloop() Function
This method is used to start the application. The mainloop() function is
an infinite loop which is used to run the application, it will wait for an event
to occur and process the event as long as the window is not closed.

SUMMARY:
With this we have completed the introduction to Tkinter, we have installed
the Tkinter module, and even know what are Windows and Widgets in
Tkinter. We also create our first Tkinter GUI app and run it. In the next
tutorial, we will learn more about Python Tkinter widgets.
Tkinter Windows, Widgets and
Frames
In this tutorial, we will cover the basics of the Tkinter module, to explain
what is a Tkinter Window, Widgets, and Frames which are the building
blocks of GUI application in Tkinter.

INTRODUCTION TO TKINTER WINDOWS AND WIDGETS


Let's dive in a little deeper, to understand some basics about the Tkinter
module and how it works.

The top-level window object in GUI Programming contains all of


the little window objects that will be part of your complete GUI.
The little window objects can be text labels, buttons, list boxes, etc.,
and these individual little GUI components are known as Widgets.
So, having a top-level window object will act as a container where you
will put all your widgets. In Python, you'd typically do so like this using
the following code: win = tkinter.Tk()
The object that is returned by making a call to tkinter.Tk() is usually
referred to as the Root Window.
Top-level windows are mainly stand-alone as part of your
application, also you can have more than one top-level window for
your GUI, but only one of them should be your root window.
First of all, you need to design all your widgets completely, and
then add the real functionality.
The widgets can either be stand-alone or can be containers. If one
widget contains other widgets, it is considered the parent of those
widgets.
Similarly, if a widget is contained within another widget, it's known
as a child of the parent, the parent is the next immediate enclosing
container widget.
The widgets also have some associated behaviors, such as when a
button is pressed, or text is filled into a text field, so we have events
attached to these actions.
The behavior of widgets generates events, and the GUI's response to
events is known as Callbacks - because they 'call' a function just to
handle the event that occurred.

TKINTER EVENT-DRIVEN PROCESSING


In Tkinter, we have windows and widgets coming together to form a GUI
application. But the GUI application is just the frontend of the application.
You would want to execute some code logic when the end-user uses those
widgets.
Whenever an action is performed on any widget, an event is generated, which
we can handle to perform any operation.
Events(behavior of widgets) can include pressing a button, movement
of the mouse, hitting the return or Enter key, gaining or losing
'focus', etc.
The entire system of events that occurs from the beginning until the
end of any GUI application is what drives it and hence it is also known
as Event-Driven Processing.
Let us take a simple mouse movement example: Suppose that
the pointer of the mouse is just sitting somewhere on top of your GUI
application. If you will move the mouse to another part of your
application, something has to cause the movement of the mouse to be
replicated by the cursor on your screen(on top of your GUI application).
These are 'cursor move' events that the system must process to
portray your cursor moving across the window. At the time you
will stop moving the mouse, no more events need to be processed, so
everything just stays still on the screen again.
Here are some basic definitions through which you will be able to understand
the concept of Windows, widgets, and frames in Tkinter.

TKINTER WINDOWS
The term "Window" has different meanings in the different contexts, But
generally "Window" refers to a rectangular area somewhere on the user's
display screen through which you can interact.
Then there comes the concept of Top Level Window in Tkinter.

TKINTER TOP-LEVEL WINDOW


The Top-Level Window is a window that exists independently on the
screen. You can decorate the top-level window with the standard frame and
controls for the desktop manager. It can usually be moved around the
desktop, and also you can resize it if you want to do so.
Then there comes the concept of Widgets. Let us try to understand it.

TKINTER WIDGETS
The term "Widgets" is a generic term that refers to the building blocks that
make up an application in a graphical user interface.
Let us list out the core widgets with their categories:
Container
Under this category, the widgets that lies are frame, labelframe,
toplevel, and paned window.
Buttons
Under the category of Buttons, there are buttons, radiobuttons,
checkbuttons (checkbox), and menubuttons.
Text Widgets
Under the category of text widgets, there are labels, messages, text.
Entry Widgets
Under this category, the widgets are scale, scrollbar, Listbox, slider,
spinbox, entry (single-line), optionmenu, text (multiline), and
canvas (vector and pixel graphics).
Now let us move on to Frames in Tkinter.

TKINTER FRAMES
A frame is basically a rectangular area that can contain other widgets. In
Tkinter, there is a Frame widget that is the basic unit of organization for
complex layouts. It is a widget which has no special styling or GUI
component of its own. It is just used to hold other Tkinter widgets in case of
complex GUI layouts.
Note: It is important to note here that whenever any widget is created, there
is also a parent-child relationship that is created. Just take an example, if you
place a button inside a frame, the frame widget is called the parent of the
Button widget.

TKINTER BASIC EXAMPLE


Let us take an example where we will create a Tkinter application with a
simple Text widget:
from tkinter import *
win = Tk() # Create the root (base) window
win.geometry("200x200")
w = Label(win, text="Hello, Welcome to Studytonight!") # Create a label with words
w.pack() # Put the label into the window
win.mainloop()# Start the event loop
The above code will create a window with the label widget and output will
look like as shown above. We have created a Tkinter Window and then added
a basic Label widget to it.

SUMMARY:
In this tutorial, we learned about the basic building blocks of GUI application
using Tkinter which are Windows, Widgets, and Frames, which are used to
develop different GUI applications. In the next tutorial, we will learn how to
create a Tkinter Window which is the starting point for any application,
because in a Tkinter Window we add all the widgets.
Tkinter Windows
In this tutorial, we will learn about Tkinter Windows in Python which is the
main Window of the GUI application inside which every other component
runs. We have covered the basic Tkinter GUI application Components in
which we have explained how Tkinter Windows, Widgets, and Frames are
building blocks of a Tkinter App.

TKINTER WINDOWS
The Tkinter window is the foundational element of the Tkinter GUI. Tkinter
window is a container in which all other GUI elements(widgets) live.
Here is the syntax for creating a basic Tkinter Window:
win = Tk()
Yes, we use the Tk() function to create our Tkinter app window in which all
the other components are added.

TKINTER WINDOWS EXAMPLE:


Here is a simple example,
from tkinter import *
win = Tk()

# run the app window


win.mainloop()
In the above example, the mainloop() function is used to run the GUI
application.

TKINTER CUSTOMIZED WINDOW


Let us now cover a basic example where we will create a Basic GUI
Application using properties like title and geometry.
Here we have the code to demonstrate the steps used in the creation of a
customized Tkinter Window:
from tkinter import *
window = Tk()
# You can add your widgets here

window.title('Hello StudyTonight')
window.geometry("300x200+10+20")
window.mainloop()
Here is what we have done in the code:
The first step is to import the Tkinter module in the code.
After importing, the second step is to set up the application object by
calling the Tk() function. This will create a top-level window (root)
having a frame with a title bar and control box with the minimize and
close buttons, and a client area to hold other widgets.
After that, you can add the widgets you might want to add in your code
like buttons, textbox, scrollbar, labels, and many more.
The window.title() function is used to provide the title to the user interface
as you can see in the output.
In the line window.geometry("300x200+10+20) ; the geometry() method defines
the width, height, and coordinates of the top left corner of the frame
as follows (all values are generally in pixels) in the same way. Here is
the syntax:
window.geometry("widthxheight+XPOS+YPOS")

After that, the application object enters an event listening loop by


calling the mainloop() method. In this way, the application is
now constantly waiting for any event generated on the elements in it.
There could be an event like text entered in a text field, a selection
made from the dropdown or radio button, single/double click actions
of the mouse, etc.
The application's functionality involves executing appropriate callback
functions in response to a particular type of event.
The event loop will terminate as soon as there is a click made on the close
button on the title bar.

SUMMARY:
In this tutorial, we learned how to create a Tkinter window to create a GUI
application. The Tkinter window contains all the widgets that make the
application.
Python Tkinter Widgets
In this tutorial, we will cover an overview of Tkinter widgets in Python.
These widgets are the functional units on any Tkinter GUI application.

TKINTER WIDGETS
There are various controls, such as buttons, labels, scrollbars, radio
buttons, and text boxes used in a GUI application. These little components
or controls of Graphical User Interface (GUI) are known as widgets in
Tkinter.

These are 19 widgets available in Python Tkinter module. Below we have all
the widgets listed down with a basic description:

Name of Widget Description


If you want to add a button in your
Button application then Button widget will be
used.

To draw a complex layout and pictures


Canvas (like graphics, text, etc.)Canvas
Widget will be used.

If you want to display a number of


options as checkboxes
CheckButton then Checkbutton widget is used. It
allows you to select multiple options at
a time.

To display a single-line text field that


Entry accepts values from the user Entry
widget will be used.

In order to group and organize another


widgets Frame widget will be used.
Frame
Basically it acts as a container that
holds other widgets.

To Provide a single line caption to


Label another widget Label widget will be
used. It can contain images too.

To provide a user with a list of options


Listbox
the Listbox widget will be used.

To provides commands to the


user Menu widget will be used.
Basically these commands are inside
Menu the Menubutton. This widget mainly
creates all kinds of Menus required in
the application.

The Menubutton widget is used to


Menubutton
display the menu items to the user.

The message widget mainly displays a


message box to the user. Basically it is
Message
a multi-line text which is non-
editable.

If you want the number of options to


be displayed as radio buttons then
Radiobutton
the Radiobutton widget will be used.
You can select one at a time.

Scale widget is mainly a graphical


Scale slider that allows you to select values
from the scale.

To scroll the window up and down


Scrollbar the scrollbar widget in python will be
used.

The text widget mainly provides


a multi-line text field to the user
Text
where users and enter or edit the text
and it is different from Entry.
The Toplevel widget is mainly used to
Toplevel provide us with a separate window
container

The SpinBox acts as an entry to the


"Entry widget" in which value can be
SpinBox
input just by selecting a fixed value of
numbers.

The PanedWindow is also


a container widget that is mainly used
PanedWindow to handle different panes. Panes
arranged inside it can either
Horizontal or vertical

The LabelFrame widget is also a


LabelFrame container widget used to mainly handle
the complex widgets.

The MessageBox widget is mainly


MessageBox used to display messages in the
Desktop applications.

Python Tkinter Button Widget


In this tutorial, we will cover the Button widget of Tkinter module in
Python.
The Button widget in Tkinter is mainly used to add a button in any GUI
Application. In Python, while using the Tkinter button widget, we can easily
modify the style of the button like adding a background colors to it, adjusting
height and width of button, or the placement of the button, etc. very easily.
You can add various types of buttons(as per your applications UI) to
your application with the help of the Button Widget.
You can also associate any method or function with a button if you
want and then that method will get called whenever you press the
button.
There are many options of button widget which you can reset or set
according to your requirements.

TKINTER BUTTON WIDGET


The syntax of the button widget is given below,
W = Button(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the buttons and these options
are written as comma-separated.
Tkinter Button Widget Options:
Following are the various options used with tkinter button widgets:

Option name Description

This option indicates the background


activebackground of the button at the time when the
mouse hovers the button.

bd
This option is used to represent the
width of the border in pixels.

bg
This option is used to represent the
background color of the button.

The command option is used to set


command the function call which is scheduled
at the time when the function is
called.

This option mainly represents the


activeforeground font color of the button when
the mouse hovers the button.

fg
This option represents the foreground
color of the button.

font
This option indicates the font of the
button.

This option indicates the height of the


button. This height indicates
height
the number of text lines in the case
of text lines and it indicates the
number of pixels in the case of
images.

image
This option indicates the image
displayed on the button.

This option indicates the highlight


higlightcolor color when there is a focus on the
button

This option is used to indicate the


way by which the multiple text lines
are represented. For left justification,
justify it is set to LEFT and it is set to
RIGHT for the right justification, and
CENTER for the center justification.

This option indicates the additional


padx padding of the button in
the horizontal direction.

This option indicates the additional


pady padding of the button in the vertical
direction.

underline
This option is used to underline the
text of the button.

This option specifies the width of the


width
button. For textual buttons, It exists as
a number of letters or for image
buttons it indicates the pixels.

In the case, if this option's value is set


Wraplength
to a positive number, the text lines
will be wrapped in order to fit within
this length.

This option's value set


to DISABLED to make the button
state unresponsive. The ACTIVE mainly
represents the active state of the
button.
We will be using the different options in examples below.
Tkinter Button Widget Example
Now let us create a simple submit button with the help of code snippet given
below:
from tkinter import *
win = Tk() ## win is a top or parent window

win.geometry("200x100")
b = Button(win, text = "Submit")

b.pack() #using pack() geometry


win.mainloop()

In the above code example, we created a simple window of given width and
height. Then we added a button widget to it with providing the window
created as the master of that button and adding a text for the button.
Tkinter Button Widget - Add style and Event handler
Below we have another code snippet where we will change the look of
buttons by adding morestyle to it. Let us see how we do it:
import tkinter
from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("300x150")
def click():
messagebox.showinfo("Hello", "Green Button clicked")
a = Button(top, text="yellow", activeforeground="yellow", activebackground="orange", pady=10)
b = Button(top, text="Blue", activeforeground="blue", activebackground="orange", pady=10)
# adding click function to the below button
c = Button(top, text="Green", command=click, activeforeground = "green",
activebackground="orange", pady=10)
d = Button(top, text="red", activeforeground="yellow", activebackground="orange", pady=10)
a.pack(side = LEFT)
b.pack(side = RIGHT)
c.pack(side = TOP)
d.pack(side = BOTTOM)
top.mainloop()

In the above code, we have added some styling using different options and
we have added an event handler to handle the click event of the 3rd button.
So whenever you will make a click on the button with text Green, you will
see a Tkinter messagebox with a message.
Python Tkinter Canvas Widget
Tkinter Canvas widget is mainly used as a general-purpose widget which
is used to draw anything on the application window in Tkinter.
This widget is mainly used to draw graphics and plots, drawings,
charts, and showing images.
You can draw several complex layouts with the help of canvas, for
example, polygon, rectangle, oval, text, arc bitmap, graphics, etc.
Canvas widget is also used to create graphical editors.
There are a number of options available to configure and control the
Canvas Widget.

TKINTER CANVAS WIDGET


The syntax of the canvas widget is given below:
w = Canvas(master, option=value)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the layout of the canvas and
these options are written as comma-separated key-values.
Tkinter Canvas Widget Options:
Following are the various options used with canvas widgets:

Option name Description

This option is mainly used to set


the width of the border in pixels.

bd The default value of 0px means no


border, 1px means thin line border and
you can increase the width of the
border.

bg
This option is used to set
the background color.

Whether to use an arrow, dot, or circle


cursor on the canvas for the cursor, this
option can be used.

This option is set to make the


confine canvas non-scrollable outside the
scroll region.

height
This option is used for controlling
the height of the canvas.

width
This option is used to set the width of
the widget.
This option indicates the highlight
highlightcolor
color when there is a focus on the
button

In the case, if the canvas is of


xscrollcommand
scrollable type, then this attribute
should act as the set() method of the
horizontal scrollbar

In the case, if the canvas is of


yscrollcommand
scrollable type, then this attribute
should act as the set() method of the
vertical scrollbar

This is option is mainly used to


scrollregion
represent the coordinates that are
specified as the tuple containing the
area of the canvas

If the value of this option is set to a


xscrollincrement
positive value then, the canvas is
placed only to the multiple of this
value.

It is mainly used for vertical


yscrollincrement movement and it works in the same
way xscrollincrement option works.

Tkinter Canvas Widget Basic Example


Let us create a simple canvas with the help of the canvas widget:
from tkinter import *
# window named top
top = Tk()
# set height and width of window
top.geometry("300x300")

#creating a simple canvas with canvas widget


cv = Canvas(top, bg = "yellow", height = "300")

cv.pack()
top.mainloop()

The above code will create a simple canvas with background


color yellow and you can draw anything above it.

TKINTER CANVAS WIDGET - PIE CHART USING ARCS


Let us create a canvas and then an arc on it with the help of code snippet
given below:
import tkinter
# init tk
root = tkinter.Tk()
# creating canvas
mCanvas = tkinter.Canvas(root, bg="white", height=300, width=300)

# drawing two arcs


coord = 10, 10, 300, 300
arc1 = mCanvas.create_arc(coord, start=0, extent=150, fill="pink")
arc2 = mCanvas.create_arc(coord, start=150, extent=215, fill="blue")

# adding canvas to window and display it


mCanvas.pack()
root.mainloop()

The above code will open a window, then add a canvas, and then draws
two arcs on it. The two arcs drawn of pink and blue color together make up
a circle as shown in the output above.

Python Tkinter Checkbutton


Widget
In this tutorial, we will cover Tkinter Checkbutton widget in Python, which is
used to create checkboxes on GUI while developing desktop applications
using Tkinter.
If you want to display a number of options in a form, where users can check
to select any option, we can use the Tkinter Checkbutton widget. It allows
you to select multiple options or a single option at a time just by clicking the
button corresponding to each option.
For example, in a form, you see option to fill in your Gender, it has options,
Male, Female, Others, etc., and you can tick on any of the options, that is a
checkbox. We use the <input> tag in HTML, to create checkbox
It can either contain text or image. There are a number of options available
to configure the Checkbutton widget as per your requirement.

TKINTER CHECKBUTTON WIDGET


The syntax of the checkbutton widget is given below:
w = CheckButton(master, option=value)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure your checkbutton widget and
these options are written as comma-separated key-value pair.
Tkinter Checkbutton Widget Options
Following are the various options used with checkbutton widgets:

Option name Description

This option indicates the background


activebackground
color of the checkbutton at the
time when the checkbutton is
under the cursor.

This option indicates the size of the


bd border around the corner. The
default size is 2 pixels.

This option is used to represent the


bg background color of the
checkbutton.
bitmap
This option is mainly used to display
the image on the button.

The command option is used to set


command
the function call which is scheduled
at the time when the state of
checkbutton is changed.

This option mainly represents the


activeforeground foreground color of the button when
the checkbutton is under the cursor.

fg
This option represents the text color
of the checkbutton.

font
This option indicates the font of the
checkbutton.

This option indicates the height of


the button. This height indicates
height
the number of text lines in the case
of text lines and it indicates the
number of pixels in the case of
images. the default value is 1.

This option indicates the image


image
representing the checkbutton.

This option helps in changing


cursor the mouse pointer to the cursor
name when it is over the
checkbutton.

This option is the color which is used


disableforeground to indicate the text of a disabled
checkbutton.

This option indicates the highlight


higlightcolor color when there is a focus on the
checkbutton

This option is used to indicate the


way by which the multiple text
lines are represented. For left
justify justification, it is set to LEFT and it
is set to RIGHT for the right
justification, and CENTER for the
center justification.

This option indicates the padding of


padx the checkbutton in the horizontal
direction.

This option indicates the padding of


pady the checkbutton in the vertical
direction.

underline
This option is used to underline the
text of the checkbutton.
This option specifies the width of the
width checkbutton. For textual buttons, It
exists as a number of letters or for
image buttons it indicates the pixels.

In the case If this option is set to an


Wraplength integer number, then the text will be
broken into the number of pieces.

This option is mainly used to


variable
represents the associated variable
that is used to track the state of the
checkbutton

The associated control variable of


checkbutton is set to 0 by default if
offvalue the button is (off). you can also
change the state of an unchecked
variable to some other one.

The associated control variable of


checkbutton will be set to 1 when it
onvalue is set (on). Any alternate value will
be supplied for the on state by setting
onvalue to that value.

This option is used to indicate the


text label just next to the checkbutton.
For multiple lines use "\n".

This option mainly used to


represent the state of the
checkbutton. Its default value=
state normal. It can be changed to
DISABLED to make the checkbutton
unresponsive. The value of this
button is ACTIVE when checkbutton
is under focus

This option indicates the color of


selectcolor the checkbutton when it is set. Its
default value is Red.

selectimage
This option indicates the image on
the checkbutton when it is set.

Tkinter Checkbutton Widget Methods:


Following are the methods used with checkbutton widgets:

Method Name Description

This method in checkbutton widget is


invoke() used to invoke the method
associated with the checkbutton.

select()
This method in the checkbutton widget is
called to turn on the checkbutton.

deselect()
This method in the checkbutton widget is
called to turn off the checkbutton.

This method in the checkbutton widget


toggle() is used to toggle between the different
Checkbuttons.

This method in the checkbutton widget is


flash() used to flashed between active and
normal colors.

TKINTER CHECKBUTTON WIDGET EXAMPLE


Below we have a basic example of this widget to gain a basic understanding
of this method:
from tkinter import *
root = Tk()
root.geometry("300x300")

w = Label(root, text ='StudyTonight', fg="Blue",font = "100")


w.pack()
Checkbutton1 = IntVar()
Checkbutton2 = IntVar()
Checkbutton3 = IntVar()

Button1 = Checkbutton(root, text = "Homepage",


variable = Checkbutton1,
onvalue = 1,
offvalue = 0,
height = 2,
width = 10)
Button2 = Checkbutton(root, text = "Tutorials",
variable = Checkbutton2,
onvalue = 1,
offvalue = 0,
height = 2,
width = 10)

Button3 = Checkbutton(root, text = "Contactus",


variable = Checkbutton3,
onvalue = 1,
offvalue = 0,
height = 2,
width = 10)
Button1.pack()
Button2.pack()
Button3.pack()
mainloop()
As you can see in the code above, three IntVar() variables are created and then
we have created three checkbutton with different text
like Homepage, Tutorials, and Contactus.
So we have created here checkbuttons using some options like text , variable ,
onvalue , offvalue , height and width . You can try using more options.

PYTHON TKINTER ENTRY WIDGET


In this tutorial, we will cover the entry widget of Tkinter in Python with its
various options, and with the help of Few Examples, we will understand the
concept in detail.
If you need to get a little bit of text from a user, like a name or an email
address or a contact number then use an Entry widget.
The Entry widget is mainly used to display a small text box that the user
can type some text into.
There are the number of options available to change the styling of
the Entry Widget.
It is important to note that the Entry widget is only used to get a single-
line text from the user because in the case of multiline text the text
widget will be used.
This widget is mainly used to accept text strings from the user.

TKINTER ENTRY WIDGET


The syntax of the entry widget is given below:
w = Entry(master, option=value)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the styling of the entry widget and these
options are written as comma-separated.
Tkinter Entry Widget Options:
Various options used with the entry widget are given below:

Option Name Description

This option is used for


bg the background color of the
widget.

This option is used for the width


bd of the border in pixels. Its
default value is 2 pixels.

This option helps in changing the


mouse pointer to the cursor
cursor type and set it to the arrow,
dot, etc.
It is important to note that By
Default, the text that is written
inside the entry box will get
exportselection automatically copied to the
clipboard. If you do not want to
copy the text then set the value
of exportselection to 0.

fg
This option is used to indicate
the color of the text.

font
This option is used to represent
the font type of the text

This option is used to


represent the color to display in
highlightbackground the traversal highlight
region when the widget does not
have the input focus.

This option is used to represent


the color to use for the traversal
highlightcolor highlight rectangle which is
drawn around the widget when
the widget has an input focus.

This option is used to specify


justify
how the text is organized in the
case if the text contains
multiple lines.
This option is used to indicate
the type of border. The default
relief value of this option is FLAT . It
has more values like GROOVE,
RAISED,RIGID .

This option is used to indicate


selectbackground the background color of the
selected text.

selectforeground
It is used to set the font of the
selected task.

This option indicates the width


selectborderwidth of the border to display around
the selected task

This option indicates the width


width of the image or width of text to
display.

With the help of this option,


you will be able to retrieve the
textvariable
current text from your entry
widget, you need to set this
option to an instance of
the StringVar class.

This option is used to show the


entry text of some other type
show instead of the string. For
example, we type the password
using stars (*).

You can link the entry widget


to the horizontal scrollbar if
xscrollcommand you want the user to enter more
text rather then the actual width
of the widget.

This option mainly represents


the color to use as a
background in the area covered
insertbackground by the insertion cursor. and thus
this color will normally
override the normal background
for the widget.

Tkinter Entry Widget Methods:


Various methods used with entry widgets are given below:

Method Name Description

This method is used to delete


delete(first, last=None) the specified characters inside the
widget.

This method is used to get


get() the entry widget's current text as
a string.

This method is used to set the


insertion cursor just before
icursor(index) the character at the specified
index.

This method is used to place the


index(index)
cursor to the left of the
character written at the specified
index.

This method is used to clear the


select_clear() selection in the case if some
selection has been done.

If there is a presence of some


select_present()
selection then this method will
return true otherwise, it will
return false .

This method is mainly used to


insert(index, s)
insert the specified string(s) before
the character placed at the
specified index

This method mainly includes the


select_adjust(index) selection of the character present
at the specified index

This method mainly sets


select_form(index)
the anchor index position to
the character specified by the
index.
This method is used to select the
select_range(start, end) characters to exist between the
specified range

This method mainly selects all the


select_to(index) characters from the beginning to
the specified index

This method is used to link the


xview(index) entry widget to a horizontal
scrollbar

This method is mainly used to make


xview_scroll(number, what) the entry widget scrollable
horizontally

TKINTER ENTRY WIDGET EXAMPLE


Below we have a basic example of the Tkinter Entry widget. Let us see the
code snippet:
from tkinter import *

win = Tk()

win.geometry("400x250")
name = Label(win, text = "Name").place(x = 30,y = 50)

email = Label(win, text = "Email").place(x = 30, y = 90)


password = Label(win, text = "Password").place(x = 30, y = 130)

submitbtn = Button(win, text = "Submit",activebackground = "red", activeforeground = "blue")


.place(x = 30, y = 170)
entry1 = Entry(win).place(x = 80, y = 50)

entry2 = Entry(win).place(x = 80, y = 90)


entry3 = Entry(win).place(x = 95, y = 130)
win.mainloop()

In the above code example, we have done the following:


Create Tkintor Labels to name the text input fields. For all the 3 text
input fields(Entry widget), we have created three labels.
We have used the place() geometry manager to place the labels on the
application window.
Then we have created a Button which is the submit button. And used
the place() geometry manager to position it on the application GUI.
And finally, we have the three Entry widgets which will create the three
text input fields. And used the place() geometry manager to position it on
the application GUI.
Python Tkinter Frame Widget
The Tkinter Frame widget is used to group and organize the widgets in a
better and friendly way. The Frame widget is basically a container (an
invisible container) whose task is to hold other widgets and arrange them
with respect to each other. The Tkinter frame widget makes up a rectangular
region on the screen.
It basically acts as a foundation class which then implements complex
widgets. It is like the HTML div tag, which is just to define divisions on a
webpage in which we have other HTML elements.

TKINTER FRAME WIDGET


The syntax of the frame widget is given below:
W = Frame(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the frame and these options are
written as comma-separated key-value pairs.
Tkinter Frame Widget Options:
Following are the various options used with frame widgets:

Name of the option Description

This option is used to represent


bd the width of the border. Its default
value is 2 pixels.

This option is used to indicate


bg the normal background color of a
widget.

With the help of this option, the


cursor
mouse pointer can be changed to the
cursor type which is set to different
values like an arrow, dot, etc.

height
This option is used to indicate
the height of the frame.

width
This option is used to indicate
the width of the frame.

This option denotes the color of


highlightbackground the background color when it is
under focus.

This option is used to specify


highlightthickness
the thickness around the
border when the widget is under the
focus.

This option specifies the type of the


relief border of the frame. Its default value
is FLAT

This option is mainly used to


highlightcolor
represent the color of the focus
highlight when the frame has
the focus.

TKINTER FRAME WIDGET EXAMPLE


Below we have a basic example where we will organize different button
widgets in a Frame widget. Let us see the code snippet given below:
from tkinter import *
root = Tk()
root.geometry("300x150")
w = Label(root, text ='StudyTonight', font = "80")
w.pack()

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

button1 = Button(frame, text ="Block1", fg ="red")


button1.pack(side = LEFT)

button2 = Button(frame, text ="Block2", fg ="brown")


button2.pack(side = LEFT)

button3 = Button(frame, text ="Block3", fg ="blue")


button3.pack(side = LEFT)
button4 = Button(bottomframe, text ="Block4", fg ="orange")
button4.pack(side = BOTTOM)

button5 = Button(bottomframe, text ="Block5", fg ="orange")


button5.pack(side = BOTTOM)
button6 = Button(bottomframe, text ="Block6", fg ="orange")
button6.pack(side = BOTTOM)

root.mainloop()
In the code example above, we have created two frame widgets and then we
have added 3 each button in those frames and have use Tkinter geometry
manager to arrange the buttons inside the application window

Python Tkinter Label Widget


In this tutorial, we will cover the Tkinter Label widget in Python, which is
used to create a Label in the GUI application in which we can show any text
or image.
The label widget in Tkinter is used to display boxes where you can place
your images and text.
The label widget is mainly used to provide a message about the other
widgets used in the Python Application to the user.
You can change or update the text inside the label widget anytime you
want.
This widget uses only one font at the time of displaying some text.
You can perform other tasks like underline some part of the text and
you can also span text to multiple lines.
There are various options available to configure the text or the part of
the text shown in the Label.

TKINTER LABEL WIDGET


The syntax of the label widget is given below,
W = Label(master,options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure the text and these options are written
as comma-separated key-value pairs.

TKINTER LABEL WIDGET OPTIONS


Following are the options used with label widgets:

Name of the
Description
option
This option is mainly used for controlling
the position of text in the provided
anchor widget size. The default value
is CENTER which is used to align the
text in center in the provided space.

This option is used for the border width


bd of the widget. Its default value is 2
pixels.

This option is used to set the bitmap


bitmap
equals to the graphical object specified
so that now the label can represent the
graphics instead of text.

bg
This option is used for the
background color of the widget.

This option is used to specify what type


of cursor to show when the mouse is
cursor moved over the label. The default of
this option is to use the standard
cursor.

This option is used to specify the


fg foreground color of the text that is
written inside the widget.

font
This option specifies the font type of
text inside the label.
height
This option indicates the height of the
widget

image
This option indicates the image that is
shown as the label.

This option specifies the alignment of


multiple lines in the label. The default
justify value is CENTER. Other values are
RIGHT, LEFT; you can justify according
to your requirement

This option indicates the horizontal


padx padding of the text. The default value of
this option is 1.

This option indicates the vertical


pady padding of the text. The default value of
this option is 1.

This option indicates the type of


relief border. The default value of this option
is FLAT

This option is set to the string variable


text and it may contain one or more than one
line of text

This option is associated with a Tkinter


textvariable
variable that is (StringVar) with a label.
If you change the value of this variable
then text inside the label gets updated.

This option is used to underline a


specific part of the text. The default
underline value of this option =-1(no underline);
you can set it to any integer value up to
n and counting starts from 0.

width
This option indicates the width of the
widget.

Rather than having only one line as the


label text, you can just break it to any
wraplength number of lines where each line has
the number of characters specified to
this option.

TKINTER LABEL WIDGET EXAMPLE


Now let us see a basic example of the label widget and the code snippet is
given below:
import tkinter
from tkinter import *
win = Tk()
var = StringVar()
label = Label( win, textvariable=var, relief=RAISED )

# set label value


var.set("Hey!? Welcome to StudyTonight")
label.pack()
win.mainloop()
In the above code, we created a simple variable StringVar() and then assigned a
value to it, and this variable is assigned as value to the textvariable option of
the Label widget.

TKINTER LABEL WIDGET - ANOTHER EXAMPLE


Below we have another code snippet for more clear understanding. Let us see
the code snippet given below:
from tkinter import *
win = Tk()

win.geometry("400x250")
#creating a label
username = Label(win, text = "Username").place(x = 30,y = 50)

#creating second label


password = Label(win, text = "Password").place(x = 30, y = 90)
submitbutton = Button(win, text = "Submit",activebackground = "red", activeforeground =
"blue").place(x = 30, y = 120)

e1 = Entry(win,width = 20).place(x = 100, y = 50)


e2 = Entry(win, width = 20).place(x = 100, y = 90)

win.mainloop()
Whenever you will run the above code, after putting values into username
and password label, when you will click on the submit button then its color
gets changed to red.
Don't worry about the Button Widget and Entry Widget used in the above
code, we will cover them shortly in the upcoming tutorials. This example is
to give you an idea about how Tkinter widgets are used to create user
interfaces for your Tkinter application.

In this tutorial, we will cover the Tkinter Listbox widget in Python which is
used to display different types of items to the user in form of a List inside a
box and the user can select the items.
The items contain the same type of font and the same font color.
It is important to note here that only text items can be placed inside
a Listbox widget.
From this list of items, the user can select one or more items according
to the requirements.
Tkinter Listbox Widget
The syntax of the Tkinter Listbox widget is given below:
W = Listbox(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the ListBox and these options are
written as comma-separated key-value pairs.
Tkinter Listbox Widget Options:
Following are the various options used with Listbox widgets:

Name of
Description
Option

bg
This option indicates the background color of the
widget.

bd
This option is used to represent the size of the border.
The default value is 2 pixels.

cursor
With the help of this option, the mouse pointer will
look like the cursor type like dot, arrow, etc.

font
This option indicates the font type of the Listbox
items.

fg This option indicates the color of the text.

This option is used to represents the count of the


height lines shown in the Listbox. The default value of this
option is 10.

highlightcolor
This option is used to indicate the color of the
Listbox items when the widget is under focus.
highlightthickness
This option is used to indicate the thickness of the
highlight.

relief
This option indicates the type of border. The default
value is SUNKEN.

selectbackground
This option is used to indicate the background
color that is used to display the selected text.

This option is used to determine the number of items


selectmode that can be selected from the list. It can set
to BROWSE, SINGLE, MULTIPLE, EXTENDED.

width
This option is used to represent the width of the
widget in characters.

xscrollcommand
This option is used to let the user scroll the Listbox
horizontally.

yscrollcommand
This option is used to let the user scroll the Listbox
vertically.

Tkinter ListBox Widget Methods:


Following are the methods associated with the Listbox widget:

Method Description
This method is mainly used to
activate(index) select the lines at the specified
index.

This method is used to return a


tuple containing the line numbers
curselection()
of the selected element or
elements, counting from 0. If
nothing is selected, return an
empty tuple.

This method is used to delete the


delete(first, last = None) lines which exist in the given
range.

This method is used to get the list


get(first, last = None) of items that exist in the given
range.

This method is used to place the


index(i) line with the specified index at
the top of the widget.

This method is used to insert the


insert(index, *elements)
new lines with the specified
number of elements before the
specified index.

This method is used to return the


nearest(y) index of the nearest line to the y
coordinate of the Listbox widget.

This method is used to adjust the


see(index)
position of the Listbox to make
the lines specified by the index
visible.

This method returns the number


size() of lines that are present in the
Listbox widget.

xview()
This method is used to make the
widget horizontally scrollable.

This method is used to make the


Listbox horizontally scrollable by
xview_moveto(fraction) the fraction of the width of the
longest line present in the
Listbox.

This method is used to make the


xview_scroll(number, what)
listbox horizontally scrollable by
the number of characters
specified.

yview()
This method allows the Listbox
to be vertically scrollable.

This method is used to make the


yview_moveto(fraction) listbox vertically scrollable by the
fraction of the width of the
longest line present in the
Listbox.

This method is used to make the


yview_scroll (number, what) listbox vertically scrollable by the
number of characters specified.

Tkinter ListBox Widget Example


Below we have a basic example using this widget:
from tkinter import * top = Tk() top.geometry("200x250") lbl = Label(top, text="List of Programming
Languages") listbox = Listbox(top) listbox.insert(1,"Python") listbox.insert(2, "Java") listbox.insert(3,
"C") listbox.insert(4, "C++") lbl.pack() listbox.pack() top.mainloop()
In the code example above, we have created a simple Listbox widget with
some items along with specifying the top list item which is the heading on the
Listbox widget.

Python Tkinter Menu Widget


In this tutorial, we will cover the Tkinter Menu widget in Python which is
used to create Menus with options for users to choose from.
The Tkinter Menu widget is used to create different types of menus in Python
Application.
The following types of menus can be created using the Tkinter Menu
widget: pop-up, pull-down, and top level.
Top-level menus are those menus that are displayed just under the title
bar of the root or any other top-level windows. For example, all the
websites have a top navigation menu just below the URL bar in the
browser.
Menus are commonly used to provide convenient access to options
like opening any file, quitting any task, and manipulating data in an
application.
Tkinter Menu Widget
The syntax of the Menu widget is given below:
W = Menu(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the menu and these options are
written as comma-separated key-value pairs.
Tkinter Menu Widget Options:
Following are the various options used with Menu widgets:

Name of the Option Description

This option is used to indicate


activebackground
the background color of the
widget when the widget is under
the focus.

This option indicates the font


activeforeground color of text of the widget when
the widget has the focus.

This option is used to indicate


the width of the border of the
widget when it is under the
activeborderwidth
mouse(when it is active). The
default value of this option is 1
pixel.

bd
This option is used to indicate
the border width of the widget

This option indicates


bg the background color of the
widget.

This option indicates the


cursor cursor when the mouse hovers
the menu.

This option indicates the text


disabledforeground color of the widget when
the widget is disabled

This option is used to indicate


font the font type of the text of
widget

This option specifies


fg the foreground color of the
widget.

This option is used to specify


relief the border type. Its default value
is RAISED.

image
This option is used to display an
image on the menu

This option can be set to any of


postcommand
the function which is called
when the mouse hovers the
menu.

The choices in the menu start


from position 1 by default. But If
tearoff we set the tearoff=1 , then choices
will start taking place from 0th
position.

This option indicates the color


selectcolor
used to display the checkbutton
or radiobutton when they are
selected.

This option is set to the title of


title the window if you want to
change the title of the window.

Tkinter Menu Widget Methods:


Following are the various methods used with Tkinter Menu widget:

Name of method Description


add_command()
This method is used to add
menu items to the menu.

add_radiobutton()
This method is used to add
the radiobutton to the menu.

This method is mainly used


add_checkbutton() to add checkbuttons to the
menu.

This method is used


to create a hierarchical menu
add_cascade() to the parent menu by
associating the given menu
to the parent menu.

This method is used to add


add_seperator() the separator line to the
menu items.

This method is used to add


add(type, options) the specific menu item to the
menu.

This method is used


delete(startindex, endindex) to delete the menu items that
exist in the specified range.

This method is used to


configure a menu item that
entryconfig(index, options) is identified by the given
index.

This method is used to get


index(item) the index of the specified
menu item.

This method is used to insert


insert_seperator(index) a separator at the specified
index.

This method is used to


invoke(index)
invoke the associated
operation with the choice
given at the specified index.

This method is used to get


type(index) the type of choice specified
by the index.

As you can see above we have so many methods associated to the Menu
widget which can be used to configure the menu as per your requirement.
Tkinter Menu Widget Example
Below we have a basic example using this widget:
from tkinter import * root = Tk() def hello(): print("hello!") menubar = Menu(root)
menubar.add_command(label="Hello StudyTonight!", command=hello)
menubar.add_command(label="Quit!", command=root.quit) root.config(menu=menubar)
root.mainloop()
After running the above code, you will see the above output. Whenever you
will click on Hello StudyTonight! menu item then it will print a hello! on
your console. While on clicking the Quit! menu item, the application will
close.

Python Tkinter Menubutton Widget


In this tutorial, we will cover the Tkinter Menubutton widget in Python which
is used to create a dropdown menu which can be clicked by the user to see
the
This widget is used to provide various types of menus in the Python
Application.
It is important to note that every Menubutton in an application is
associated with a Menu widget and that in return can display the choices
for that menubutton whenever the user clicks on it.
The Tkinter Menubutton widget provides the user with an option to
select the appropriate choice that exists within the application.
Tkinter Menubutton Widget
The syntax of the Tkinter Menubutton widget is given below:
W = Menubutton(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the menubuttons and these options
are written as comma-separated key-value pairs.
Tkinter Menubutton Widget Options:
Following are the various options used with Tkinter Menubutton widgets:

Option name Description

This option indicates the


activebackground
background color of the
menubutton at the time when the
mouse hovers the menubutton.

This option is used to represent the


bd width of the border in pixels. The
default value is 2 pixels.

This option will be set to the


bitmap graphical content which is to be
displayed to the widget.

bg
This option is used to represent the
background color of the widget.
This option indicates the
cursor cursor when the mouse hovers the
menubutton.

This option mainly represents the


activeforeground
font color of the widget at the
time when the widget is under the
focus

fg
This option represents
the foreground color of the widget.

With the help of this option, you


can specify the direction so that
menu can be displayed to the
direction specified direction of the button.
You can Use LEFT, RIGHT, or
ABOVE to place the widget
accordingly.

This option indicates the text color


disabledforeground of the widget when the widget is
disabled

This option indicates the height of


the menubutton. This height
height
indicates the number of text lines in
the case of text lines and it
indicates the number of pixels in
the case of images.
image
This option indicates the image
displayed on the menubutton.

This option indicates the highlight


higlightcolor color when there is a focus on the
button

This option is used to indicate the


way by which the multiple text
lines are represented. For left
justify justification, it is set to LEFT and it
is set to RIGHT for the right
justification, and CENTER for the
center justification.

This option indicates the additional


padx padding of the widget in
the horizontal direction.

This option indicates the additional


pady padding of the widget in
the vertical direction.

This option is used to indicate the


menu menu associated with the
menubutton

This option specifies the width of


the widget. For textual buttons, It
width exists as a number of letters or for
image buttons it indicates the pixels

In this case, if this option's value


Wraplength
is set to a positive number, the text
lines will be wrapped in order to fit
within this length.

As the normal state of menubutton


state is enabled.It can be set to disable to
make the menubutton unresponsive.

text
This option is used to indicate the
text on the widget.

A control variable of
class StringVar can be associated
textvariable with this menubutton. If you
will set that control variable then it
will change the displayed text.

This option is mainly used to


represent the index of the character
underline
in the text of the widget which is to
be underlined. The indexing
generally starts with zero in the
text.

This option is used to specify the


relief border type. Its default value is
RAISED

Tkinter Menubutton Widget Example


Now let us see a code snippet for the Tkinter Menubutton widget:
from tkinter import * import tkinter win = Tk() mbtn = Menubutton(win, text="Courses",
relief=RAISED) mbtn.grid() mbtn.menu = Menu(mbtn, tearoff = 0) mbtn["menu"] = mbtn.menu
pythonVar = IntVar() javaVar = IntVar() phpVar = IntVar()
mbtn.menu.add_checkbutton(label="Python", variable=pythonVar)
mbtn.menu.add_checkbutton(label="Java", variable=javaVar)
mbtn.menu.add_checkbutton(label="PHP", variable=phpVar) mbtn.pack() win.mainloop()
The output of the above code is as follows:

You can try the above example by yourself. Whenever you will execute the
above code, you will see there is a Tkinter menubutton named Courses on a
window whenever you will click on it then it will show you a drop-down
menu like this:

Summary:
In this tutorial, we covered the Tkinter Menubutton widget which is used to
create drop-down menus in a Tkinter application.

Python Tkinter Message Widget


In this tutorial, we will learn about the Tkinter Message widget in Python
which is used to show some text message on the GUI application that you
create using Tkinter.
The Tkinter Message Widget in Python is mainly used to show some
message to the user who is using the application.
The message displayed by the Tkinter Message Widget is of non-
editable type and it can be in multiline.
The message displayed by the Tkinter Message widget contains single
font text.
The functionality of this widget is very similar to the Tkinter Label
widget, but there is a difference and that is the message widget
can automatically wrap the text.
Tkinter Message Widget
The syntax of the Tkinter Message widget is given below:
W = Message(master,options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the message and these options are
written as comma-separated key-value pair.

Tkinter Message Widget Options:


Following are the various options used with the Tkinter Message widget:

Name of the option Description

It is mainly used to decide the exact


anchor
position of the text within the
provided space. The default value
of this option is CENTER.
bg This option denotes the background
color of the widget.

This option is used to indicate the


bd border width of the widget. The
default value of this is 2 pixels.

In order to display graphics on the


bitmap
widget, this option will be used.
You can set it to any graphical or
image object.

With the help of this option, the


cursor
mouse pointer will be changed to a
specific cursor type like an arrow,
dot, etc.

fg
This option is used to indicate the
font color of the widget text.

font
This option is used to indicate the
font type of the widget text.

This option is used to indicate the


height vertical dimension of the message
widget.

image
This option is used to indicate the
image on the widget.
This option is used for
justify
the justification of the text on the
widget. It can be CENTER, LEFT,
RIGHT

This option is used for


padx the horizontal padding of the
widget.

pady
This option is used for the vertical
padding of the widget.

This option is used to specify the


relief border type. Its default value is
FLAT

This option can be set to an


existing number in order to specify
underline that nth letter of the string will be
underlined. Its default value
is -1 which indicates no underline.

If you want to display one or more


lines of text in a label widget you
text
need to set this option to a string
containing the text. You can use
"\n" just in order to enter multiple
lines
This option is used to control the
text represented by the widget.
textvariable
The textvariable can be set to the text
that is needed to be shown on the
widget.

This option is used to indicate the


width
horizontal dimension of the widget
in the number of characters and not
in pixels.

This option is used to wrap the


text to the number of lines just by
wraplength setting this option to the desired
number so that each line contains
only that number of characters.

Tkinter Message Widget Example


Below we have a basic example for the Tkinter Message widget:
from tkinter import * win = Tk() win.geometry("300x200") w = Label(win, text ='StudyTonight', font =
"90",fg="Navyblue") w.pack() msg = Message(win, text = "Best place to learn coding online")
msg.pack() win.mainloop()
In the code example above, we have created a simple label widget and a
message widget with some text message in it.

Python Tkinter Radiobutton


Widget
In this tutorial, we will cover the Tkinter Radiobutton widget in Python,
which is used when we want to add a radio button to the GUI of our
application.
Tkinter radiobutton widget is used to implement multiple-choice options that
are mainly created in user input forms.
This widget offers multiple selections to the user and allows the user to
select only one option from the given ones. Thus it is also known as
implementing one-of-many selection in a Python Application.
Also, different methods can also be associated with radiobutton.
You can also display multiple line text and images on the radiobutton.
Each radiobutton displays a single value for a particular variable.
You can also keep a track of the user's selection of the
radiobutton because it is associated with a single variable
Tkinter Radiobutton Widget
The syntax of the Radiobutton widget is given below:
W = Radiobutton(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the radiobutton and these options
are written as comma-separated key-value pairs.
Tkinter Radiobutton Widget Options:
Following are the options used with Tkinter Radiobutton widgets:

Name of the option Description

This option is used to represent


the exact position of the
text within the widget, in the
anchor case of the widget contains more
space than the requirement of
the text. The default value of
this option is CENTER.

bg
This option represents the
background color of the widget.

This option represents the


activebackground background color of the
widget when it is under focus.
This option represents the font
activeforeground color of the widget when it is
under focus.

borderwidth
This option is used to represent
the size of the border.

If you want to display graphics


bitmap
on the widget then you can set
this widget to any graphical or
image object.

This option is used to set the


command
procedure which must be called
every time when the state of the
radiobutton is changed.

This option will convert the


cursor
mouse pointer to the specified
cursor type and it can be set to
an arrow, dot, etc.

This option is used to represent


font the font type of the text of the
widget.

This option is used to represent


fg
the foreground color of the text
of the widget.

height
This option indicates the vertical
dimension of the widget

This option indicates


width
the horizontal dimension of the
widget and it is represented as
the number of characters.

This option represents the


padx horizontal padding of the
widget.

pady
This option represents the
vertical padding of the widget

This option is used to represent


highlightcolor
the color of the focus
highlight when the widget is
under the focus

This option is used to represent


highlightbackground
the color of the focus
highlight when the widget is not
under the focus.

If you want to display an image


on the widget then this option
image will be set to an image rather
than the text

This option is used to represent


the justification of the multiline
justify text. The default value
is CENTER. Other values
are LEFT, RIGHT.

This option is used to represent


relief the type of border. The default
value is FLAT.

This option indicates the color


selectcolor of the radiobutton when it is
selected

This option indicates the image


selectimage to be displayed on the
radiobutton when it is selected

This option is used to represent


the state of the radio button. The
default state of the Radiobutton
state is NORMAL. You can also set
the state to DISABLED in order
to make the radiobutton
unresponsive.

This option indicates the text to


text be displayed on the radiobutton.

This option is used to control


the text represented by the
textvariable widget. The textvariable can
be set to the text that is needed
to be shown on the widget.

This option can be set to an


existing number in order to
underline
specify that nth letter of the
string will be underlined. Its
default value is -1 which
indicates no underline

This option is also known as


the control variable which is
variable used to keep the track of user's
choices. Thus this variable is
shared among all radiobuttons.

This option of each radiobutton


value
is assigned to the control
variable when it is turned on by
the user.

This option is used to wrap the


text to the number of lines just
by setting this option to the
wraplength
desired number so that each line
contains only that number of
characters.

Tkinter Radiobutton Widget Methods:


Following are the various methods used with the Tkinter Radiobutton
widgets:

Method
Description
Name

deselect()
This method is used to deselect or turns
off the radio button

select()
This method is used to select the radio
button

This method is generally used to call a


invoke() function when the state of radio button
gets changed.

This method is generally used to flash


flash() the radio button between its normal and
active colors many times.

Tkinter Radiobutton Widget Example


Below we have a basic example for the radio button widget. let us see the
code snippet for the Radiobutton widget:
#firstly ImportTkinter module
from tkinter import *
from tkinter.ttk import *

# Creating parent Tkinter window


win = Tk()
win.geometry("200x200")
# let us create a Tkinter string variable
# that is able to store any string value
v = StringVar(win, "1")

# here is a Dictionary to create multiple buttons


options = {" Option A" : "1",
"Option B" : "2",
"Option C" : "3",
"Option D" : "4"
}

# We will use a Loop just to create multiple


# Radiobuttons instaed of creating each button separately
for (txt, val) in options.items():
Radiobutton(win, text=txt, variable=v, value=val).pack(side = TOP, ipady = 4)
mainloop()
The above code will give the following output:

Note: If you will try above code snippet by yourself then you will see that in
the output you can select only one button at a time.
TKINTER RADIOBUTTON WIDGET ANOTHER EXAMPLE
Below we have another example of this widget where we will add styling to
radiobutton using style class:
from tkinter import *
from tkinter.ttk import *

win= Tk()
win.geometry('200x200')
v = StringVar(win, "1")
# we will add Style class to add style to Radiobutton
style = Style(win)
style.configure("TRadiobutton", background = "light blue",
foreground = "orange", font = ("arial", 14, "bold"))

# Dictionary to create multiple buttons


values = {"RadioButton 1" : "1",
"RadioButton 2" : "2",
"RadioButton 3" : "3"
}
for (text, value) in values.items():
Radiobutton(win, text = text, variable = v,
value = value).pack(side = TOP, ipady = 3)
mainloop()
The above code will change the font style as well as background and
foreground colors. In the above TRadiobutton is used in style class, which
automatically applies styling to all the available Radiobuttons.

PYTHON TKINTER SCALE WIDGET


In this tutorial, we will cover the Tkinter Scale widget in Python which is
used to add a graphical slider object which the user can slide and choose a
number, as a numeric value is attached to this slider scale and as you move
the slider up/down or right/left the numeric value attached to it increases or
decreases and you can set the slider to the value you wish to select.
The sliding bar provided by the scale widget is helpful in selecting the
values just by sliding from left to right or top to bottom depending
upon the orientation of the sliding bar in our application.
The scale widget is used as an alternative to the Entry widget if the
purpose of the Entry widget is to take numeric input from user within a
given range of values.
You can also control minimum and maximum values along with the
resolution of the scale.

TKINTER SCALE WIDGET


The syntax of the Tkinter Scale widget is given below:
W = Scale(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the layout of the scale widget and
these options are written as comma-separated key-values.

TKINTER SCALE WIDGET OPTIONS:


Following are the various options used with Tkinter Scale widget:

Name of the option Description

This option represents the


activebackground background color of the widget
when it is under focus.

This option represents


bg the background color of the
widget

This option represents the


bd border size of the widget. The
default value is 2 pixels.

With the help of this option, the


mouse pointer will be changed
cursor
to a specific cursor type and it
can be an arrow, dot, etc.

This option will be set to the


procedure which is called every
time when we move the
command slider. If we move the slider
rapidly, the callback to
the procedure is done when it
settles.

When the control variable


which is used to control the
scale data is of string type, then
digits this option is mainly used to
specify the number of digits
when the numeric scale
is converted to a string.

fg
This option indicates the
foreground color of the text

font
This option indicates the font
type of the text

from_
This option is used to represent
one end of the widget range.

This option indicates the


highlightcolor highlight color when the widget
is under the focus
This option indicates the
highlightbackground highlight color when the widget
is not under the focus

This option can be set to some


text which then can be shown
as a label with the scale. If
label the scale is horizontal then it is
shown in the top left corner or if
the scale is vertical then it
shown in the top right corner.

This option indicates the length


of the widget. It represents the X
dimension if the scale is in the
length horizontal direction and it
represents the Y dimension if
the scale is in a vertical
direction.

This option is used to specify the


relief border type. Its default value is
FLAT

This option can be set to


orient
either horizontal or vertical
depending upon the type of the
scale.

This option will be set to


resolution the smallest change which is
made to the value of the scale
This option is mainly used to tell
the duration up to which the
repeatdelay
button is to be pressed before
the slider starts moving in that
direction repeatedly. its default
value is 300 ms

This option represents the length


of the slider window along the
sliderlength
length of the scale. Its default
value is 30 pixels. Also, you can
change it to the appropriate
value.

By default, the value of the scale


showvalue
is shown in the text form, also
we can set this option to 0 in
order to suppress the label.

By default, the state of the scale


state
widget is active. To make it
unresponsive you can also set it
to DISABLED

This option is used to represent


width the width of the trough part of
the widget

This option is used to represent


variable the control variable for the
scale
This option is used represents a
to
float or integer value that
specifies the other end of the
range represented by the scale

Generally, the focus will cycle


takefocus
through the scale widgets. If
you don't want this behavior you
can set this option to 0.

With the help of this


option, scale values are
tickinterval displayed on the multiple of the
specified tick interval. The
default value of this option is 0.

troughcolor
This option is used to set the
color for the trough

TKINTER SCALE WIDGET METHODS


Following are the few methods used with Scale widgets:
get() :
This method is used to get the current value of the scale.

set(value) :

This method is used to set the value of the scale.

TKINTER SCALE WIDGET - HORIZONTAL EXAMPLE


Below we have a basic example where we will create a horizontal slide bar.
from tkinter import *

win = Tk()
win.geometry("200x100")
v = DoubleVar()

scale = Scale( win, variable=v, from_=1, to=50, orient=HORIZONTAL)


scale.pack(anchor=CENTER)
btn = Button(win, text="Value")
btn.pack(anchor=CENTER)

label = Label(win)
label.pack()
win.mainloop()

In this tutorial, we have created a horizontal Scale widget. If you see in the
code, we have specified the orient as HORIZONTAL for this. We have also
specified the range of numeric values for the slider scale.

TKINTER SCALE WIDGET - VERTICAL EXAMPLE


Below we have another example where we will create a vertical slider:
from tkinter import *

win = Tk()
win.geometry("400x300")
v = DoubleVar()

def show():
sel = "The Vertical Scale Value is = " + str(v.get())
# adding scale value to label to show
scale_val.config(text=sel, font=("Courier", 16))
scl = Scale(win, variable=v, from_=60, to=1, orient=VERTICAL)
mainlabel = Label(win, text="The Vertical Slider")

btn = Button(win, text ="Show Slider Value",


command = show,
bg = "darkblue",
fg = "white")
# creating another label to show the scale value
scale_val = Label(win)

scl.pack(anchor = CENTER)
mainlabel.pack()
btn.pack()
scale_val.pack()
win.mainloop()

You can move the slider from bottom to top as it is a vertical slider. In the
given example, we have also added a button to our application, and we
have defined a function show() that is attached to the button widget as
an event handler. So after the user uses the slider to select any value, and
then clicks on the button, the value will be displayed in a Label widget below
the button.

PYTHON TKINTER SCROLLBAR WIDGET


In this tutorial, we will cover the Tkinter Scrollbar widget in Python, using
which we can add a scrollbar to the user interface of our Tkinter application.
To scroll up or down or right or left the content in a Python desktop
application, the Tkinter Scrollbar widget is used.
To scroll the content of other widgets like Listbox, canvas, etc we use
this widget.
Both Horizontal and Vertical scrollbars can be created in the Trinket
Entry widget.
Below we have an image showing scrollbar widget used with a Listbox:
TKINTER SCROLLBAR WIDGET
The syntax of the Scrollbar widget is given below:
W = Scrollbar(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure your scrollbar widget and
these options are written as comma-separated key-value pairs.
Tkinter Scrollbar Widget Options:
Following are the various options used with Tkinter Scrollbar widgets:
Name of the Option Description

This option represents the


activebackground background color of the
widget when it is under focus.

This option represents


bg the background color of the
widget

This option represents the


bd border size of the widget. The
default value is 2 pixels.

With the help of this option, the


cursor
mouse pointer will be changed
to a specific cursor type and it
can be an arrow, dot, etc.

This option will be set to the


command
procedure associated which is
called every time the scrollbar
is moved.

This option mainly represents


the border width around the
elementborderwidth arrowheads and the slider. The
default value of this option is
-1.

This option represents the


highlightthickness thickness of the focus
highlights

This option indicates the


highlightbackground
highlight color when
the widget is not under the
focus

This option indicates the


highlightcolor highlight color when
the widget is under the focus

This option is used to control


the behavior of the scroll
jump
jump. If this option is set to 1,
then the callback is called at the
time when the user releases
the mouse button.

This option can be set to


orient
either horizontal or vertical
depending upon the orientation
of the scrollbar.

width
This option represents the
width of the scrollbar.

troughcolor
This option is used to set the
color for the trough

By default, you can tab the


takefocus focus through this widget. If
you don't want this behavior
you can set this option to 0.

This option is mainly used


to tell the duration up to
which the button is to be
repeatdelay pressed before the slider starts
moving in that direction
repeatedly. its default value
is 300 ms

repeatinterval
The default value of this option
is 100

Tkinter Scrollbar Widget Methods:


Few methods used with Tkinter Scrollbar widgets are:
get() :
This method returns the two numbers
suppose a and b which represents the current position of the
scrollbar.
set(first, last) :

This method is used to connect the scrollbar to any other widget.


That is yscrollcommand or xscrollcommand of the other widget to this
method.

TKINTER SCROLLBAR WIDGET EXAMPLE


Below we have a basic example of a scrollbar widget.
from tkinter import *

win= Tk()
sbb = Scrollbar(win)
sbb.pack(side = RIGHT, fill = Y)
mylist = Listbox(win, yscrollcommand = sbb.set)
for line in range(45):
mylist.insert(END, "Value " + str(line))
mylist.pack(side = LEFT)
sbb.config(command = mylist.yview)

mainloop()

As you can see in the above code, we have created a Listbox widget with
numbers as list items in it. Then we have created a Scrollbar widget and have
used the yscrollcommand option of the Listbox widget to set the Scrollbar
widget with it. We have used the Scrollbar widget's set function here.

Python Tkinter Text Widget


In this tutorial, we will cover the Tkinter Text widget in Python. If you want
a text-editor in your desktop application then you can use the Tkinter Text
widget.
The text widget is used to provide a multiline textbox (input box)
because in Tkinter single-line textbox is provided using Entry widget.
You can use various styles and attributes with the Text widget.
You can also use marks and tabs in the Text widget to locate the
specific sections of the text.
Media files like images and links can also be inserted in the Text
Widget.
There are some variety of applications where you need multiline text
like sending messages or taking long inputs from users, or to show
editable long format text content in application, etc. use cases are
fulfilled by this widget.
Thus in order to show textual information, we will use the Text widget.

TKINTER TEXT WIDGET


The syntax of the Text widget is given below:
W = Text(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure the text editor and these options are written
as comma-separated key-value pairs.

TKINTER TEXT WIDGET OPTIONS:


Following are the various options used with Text widgets:

Name of the option Description

bd
This option represents the
border width of the widget.

This option indicates the


bg background color of the
widget.

This option is used to export


the selected text in the
selection of the window
exportselection
manager. If you do not want to
export the text then you can
set the value of this option to
0.

This option will convert the


cursor
mouse pointer to the specified
cursor type and it can be set
to an arrow, dot, etc.

font
This option is used to indicate
the font type of the text.

fg
This option indicates the text
color of the widget

This option indicates the


height
vertical dimension of the
widget and it is mainly in the
number of lines.

This option indicates


highlightbackground
the highlightcolor at the time
when the widget isn't under
the focus.

This option is used to indicate


higlightthickness
the thickness of the highlight.
The default value of this
option is 1.
This option indicates the color
highlightcolor of the focus highlight when
the widget is under the focus.

This option is used to


insertbackground represent the color of the
insertion cursor.

This option indicates the


padx horizontal padding of the
widget.

This option indicates the


pady vertical padding of the
widget.

This option indicates the type


relief
of the border of the widget.
The default value of this option
is SUNKEN.

If the value of this option is set


to DISABLED then
state the widget becomes
unresponsive to mouse and
keyboard

This option is used to


tabs
control how the tab character
is used for the positioning of
the text
This option represents the
width width of the widget and this
is in characters.

To wrap wider lines into


multiple lines this option is
wrap
used. The default value of this
option is CHAR which breaks
the line which gets too wider
at any character

If you want to make the Text


widget horizontally
xscrollcommand scrollable, then you can set
this option to the set() method
of Scrollbar widget

If you want to make the Text


widget vertically scrollable,
yscrollcommand then you can set this option to
the set() method of Scrollbar
widget

This option indicates the


spacing1 vertical space to insert above
each line of the text.

This option is used to specify


how much extra vertical
space to add
spacing2
between displayed lines of text
when a logical line wraps. The
default value of this option is
0

This option indicates the


spacing3 vertical space to insert below
each line of the text.

This option indicates the


selectbackground background color of the
selected text.

This option indicates the


selectborderwidth width of the border around
the selected text.

This option represents the time


insertofftime
amount in Milliseconds and
during this time the insertion
cursor is off in the blink cycle

This option represents the time


insertontime
amount in Milliseconds and
during this time the insertion
cursor is on in the blink cycle

In order to represent the width


of the border around the
insertborderwidth cursor, we use this
option. The default value of
this option is 0.
TKINTER TEXT WIDGET METHODS:
Some methods used with the text widget are given below:

Method Description

index(index)
This method is used to
get the specified index.

This method returns true


or false on the basis that
see(index) if the string is visible or
not at the specified
index.

This method is used to


insert(index,string) insert a string at the
specified index.

This method returns the


get(startindex,endindex) characters in the
specified range

This method deletes the


delete(startindex,endindex) characters in the
specified range

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:
tag_config()
To configure the properties of the tag this method will be used.
tag_add(tagname, startindex, endindex)
This method is mainly used to tag the string that is present at the
specified index.
tag_delete(tagname)
This method is mainly used to delete the specified tag.
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:
index(mark)
This method is mainly used to get the index of the mark specified.
mark_names()
This method is used to get all the names of the mark in the range in
the text widget.
mark_gravity(mark, gravity)
To get the gravity of the given mark this method will be used.
mark_set(mark, index)
This method is used to inform the new position of the given mark.
mark_unset(mark)
In order to remove the given mark from the text this method will be
used.

TKINTER TEXT WIDGET EXAMPLE


Let us discuss a basic example for the text widget. The code snippet for the
example of the text widget is given below:
import tkinter as tk
from tkinter import *

win = Tk()
#to specify size of window.
win.geometry("250x170")
# To Create a text widget and specify size.
T = Text(win, height = 6, width = 53)
# TO Create label
l = Label(win, text = "Quote for the Day")
l.config(font =("Courier", 14))

Quote = """Success usually comes to those who are too busy to be looking for it"""
# Create a button for the next text.
b1 = Button(win, text = "Next", )

# Create an Exit button.


b2 = Button(win, text = "Exit",
command = win.destroy)

l.pack()
T.pack()
b1.pack()
b2.pack()

# Insert the Quote


T.insert(tk.END, Quote)
tk.mainloop()
The output for the code snippet given above is as follows:
If you want to destroy this window just click on the Exit button.

Python Tkinter Toplevel Widget


In this tutorial, we will cover the Tkinter Toplevel widget in Python which is
used to create and display top-level windows other than the application
window.
With the help of the Tkinter Toplevel widget, you can provide extra
information to the user in a separate window on top of the parent
window.
This top-level window created using the Toplevel widget is directly
organized and managed by the window manager.
It is not necessary for the top-level windows to have parents on their
top.
You can create multiple top-level windows one over the other.
Top-level windows created using Top-level widgets contain title bars,
borders, and some window decorations too.
With the help of this widget, you can provide pop-ups, some extra
information, or some widgets on the new window if you want.

PYTHON TKINTER TOPLEVEL WIDGET


The syntax of the Tkinter Toplevel widget is given below:
W = Toplevel(master,options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure your Toplevel widget and
these options are written as comma-separated key-value pairs.

TKINTER TOPLEVEL WIDGET OPTIONS:


Following are the various options used with Tkinter Toplevel widgets are
given below:
Name of the Description
option

bd
To represent the border size of the
window

bg
To represent the background color
of the window

Generally, the text selected in the


text widget is simply exported to be
class_
selected to the window
manager. You can also set the value
of this option to 0 to make this kind
of behavior false.

This option will convert the mouse


cursor
pointer to the specified cursor type
and it can be set to an arrow, dot,
etc.

width
This option is used to represent the
width of the window

height
This option is used to represent the
height of the window

This option indicates the font


font type of the text to be inserted into
the widget.
fg
This option is used to indicate the
foreground color of the widget.

relief
This option indicates the type of the
window.

TKINTER TOPLEVEL WIDGET METHODS:


Following are the various methods used with Tkinter Toplevel widgets are
given below:

Method Description

title(string)
This method is used to define
the title for the window.

This method is used to delete


withdraw() the window but it would not
destroy the window.

positionfrom(who)
This method is used to define
the position controller

sizefrom(who)
This method is used to define
the size controller.

This method is used to declare


minsize(width,height) the minimum size for the
window
This method is used to declare
maxsize(width,height)
the maximum size for the
window

This method is used


resizable(width,height)
to control whether the
window can be resizable or
not.

This method is used to


transient([master]) convert the window into a
temporary window

This method is used


iconify() to convert the top-level
window into an icon.

deiconify()
This method is mainly used
to display the window.

To indicate a system-
frame() dependent window
identifier this method is used.

This method is used to add a


group(window) top-level window to
a specified window group

This method is used


protocol(name,function)
to indicate a function which
will be called for the specific
protocol

This method is used to get the


current state of the window.
state() Some Possible values of this
option are normal, iconic,
withdrawn, and icon.

TKINTER TOPLEVEL WIDGET EXAMPLE


Below we have a basic example where we will create a simple top-level
window.
from tkinter import *
win = Tk()

win.geometry("200x200")
def open():
top = Toplevel(win)
top.mainloop()

btn = Button(win, text="open", command=open)


btn.place(x=75, y=50)

win.mainloop()
In the code above, we have created a Toplevel widget that is created and
started when the Button is clicked.

Python Tkinter Spinbox Widget


In this tutorial, we will cover Tkinter Spinbox widget in Python with its
syntax and few examples. The Spinbox widget in Tkinter in Python is used
to select a value from the specified given range of values.
It is different from the Tkinter Scale widget (Scale widget being more
stylish) in terms of style, but more or less, fulfils the same purpose.
For example, when you want to have a dropdown of numerical values like
year of birth (from 1950 to 2020) or a dropdown for user to choose their age,
we can use the Tkinter Spinbox widget.
This widget is an alternative to Entry widget, when we want user to
enter a numeric value within a specific range.
This widget is used only in the case where users need to chose from a
given range of choices.
Tkinter Spinbox Widget
The syntax of the Spinbox widget is given below:
w = Spinbox(master, option=value)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure your spinbox widget and
these options are written as comma-separated key-value pairs.
Tkinter Spinbox Widget Options:
Following are the various options used with Tkinter Spinbox widgets:

Name of the
Description
Option

bg
This option is used for the
background color of the widget.

bd
This option is used for
the border width of the widget

This option is used to indicate


the associated function with the
command widget which is called every time
the state of the widget is
changed.

With the help of this option,


cursor
your mouse pointer type can be
changed to the cursor type that is
assigned to this option.
This option indicates
activebackground the background color of the
widget when it is under the focus

This option is used to indicate


disabledbackground the background color of the
widget when it is disabled.

This option is used to indicate


disabledforeground the foreground color of the
widget when it is disabled.

font
This option specifies the font
type of text inside the widget.

This option specifies


fg the foreground color of the
widget.

This option is mainly used for


format the format string. There is no
default value of this option.

from_
This option is used to indicate
the starting range of the widget

This option specifies


the alignment of multiple
justify lines in the label. The default
value is LEFT. Other values are
RIGHT and CENTER.

This option indicates the type of


relief border. The default value of this
option is SUNKEN.

This option is used to represent


the state of the widget. The
state default value of this option
is NORMAL. Other values are
"DISABLED", "read-only", etc.

This option is used to


validate control how to validate the
value of the widget

This option represents


to
the maximum limit of the
widget value. The other value is
specified by the from_ option

This option is mainly used


repeatdelay
to control the autorepeat
button. The value here is in
milliseconds.

This option is similar


repeatinterval
to repeatdelay option. The value
here is also given in
milliseconds.
This option is associated
validatecommand with the function callback that
is used for the validation of the
content of the widget.

This option is mainly used with


xscrollcommand
the set() method of the scrollbar
widget to make this widget
horizontally scrollable

This option is mainly used


wrap to wrap-up the up and down
button of the Spinbox

width
This option indicates the width
of the widget.

vcmd
This option is similar to
validatecommand.

This option represents


values the tuple which contains
the values for the widget

It is a control variable that is


textvariable used to control the text of the
widget

TKINTER SPINBOX WIDGET METHODS:


Following are the various methods used with Tkinter Spinbox widget:
Method Name Description

This method is used to invoke


invoke(element) the callback that is associated
with the widget.

We use this method mainly to


insert(index,string) insert the string at the given
specified index

To get the absolute value of


index(index) the given index this method
will be used

This method is used


identify(x,y) to identify the widget's
element in the specified range

This method is used to get the


get(startindex, endindex) characters in the specified
range

This method is used to delete


delete(startindex, endindex) the characters in the specified
range

TKINTER SPINBOX WIDGET EXAMPLE


Below we have a basic example of the Spinbox widget. Let us see the code
snippet given below:
from tkinter import *
win = Tk()
win.geometry("300x200")
w = Label(win, text ='StudyTonight', fg="navyblue",font = "50")
w.pack()

sp = Spinbox(win, from_= 0, to = 50)


sp.pack()
win.mainloop()

In the above code, we created a simple application window, with a Label


widget and a Spinbox widget with range from 0 to 50.

Python Tkinter PanedWindow


Widget
In this tutorial, we will cover the Tkinter PanedWindow widget which is
mainly a container widget containing one or more than one child
widgets which are also known as Panes.
This widget arranges child widgets either in a vertical or in a horizontal
manner.
It is also known as the Geometry Manager widget.
This widget is used to implement different layouts in a Python desktop
application created using the Tkinter module.
The child widgets inside the PanedWindow widget can be resized by
the user by moving separator lines sashes using the mouse.
You can implement multiple panes using the PanedWindow widget.
Here is a simple Tkinter application window with three widgets stacked
vertically inside a PanedWindow widget.

TKINTER PANEDWINDOW WIDGET


The syntax of the PanedWindow widget is given below:
W = PanedWindow(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the PanedWindow and these
options are written as comma-separated.

TKINTER PANEDWINDOW WIDGET OPTIONS:


Following are the various options used with PanedWindow widget:

Name of the Description


Option

This option is used to represent the 3D border size


of the widget. The default value of this option
bd indicates that the trough contains no border and
the arrowheads and slider contain the 2-pixel
border size.

bg
This option represents the background color of the
widget.

This option will convert the mouse pointer to the


cursor specified cursor type and it can be set to an arrow,
dot, etc.

This option is used to indicate the border width of


borderwidth the widget. The default value of this option is 2
pixels.

To represents the distance between the handle and


the end of the sash we use this option. In horizontal
handlepad orientation, it is the distance between the top of the
sash and the handle. The default value of this
option is 8 pixels

This option represents the height of the widget. If


height we do not specify the height then the height will be
calculated by the height of the child widgets.

This option represents the size of the handle and its


handlesize
default value is 8 pixels. Also, the handle will
always be in square

The value of this option will be set


to HORIZONTAL if we want to place the child
orient windows side by side. If we want to place the child
windows from top to bottom then the value of this
option will be set to VERTICAL.

This option is used to represent the padding to be


sashpad done around each sash. The default value of this
option is 0.

sashwidth
This option indicates the width of the sash. The
default value of this option is 2 pixels.

This option is used to represent the type of border


sashrelief around each of the sash. The default value of this
option is FLAT

To display the handles, the value of this option


showhandle should be set to true. The default value of this
option is false.

This option represents the width of the widget. If


width we do not specify the height then the height will be
calculated by the height of the child widgets.

relief
This option indicates the type of border. The
default value of this option is FLAT.
TKINTER PANEDWINDOW WIDGET METHODS:
Following are some methods used with PanedWindow widget:

Method Name Description

This method is mainly


config(options)
used to configure any
widget with some
specified options.

This method is used to get


get(startindex,endindex) the text at the specified
given range.

This method is used to add


add(child,options) a window to a parent
window.

TKINTER PANEDWINDOW WIDGET EXAMPLE


Below we have a basic example for the understanding of the PanedWindow
widget. Let us see the code snippet given below:
from tkinter import *

# event handler for button


def addition():
x = int(e1.get())
y = int(e2.get())
leftdata = str(x+y)
leftinput.insert(1, leftdata)
# first paned window
w1 = PanedWindow()
w1.pack(fill=BOTH, expand=1)

leftinput = Entry(w1, bd=5)


w1.add(leftinput)
# second paned window
w2 = PanedWindow(w1, orient=VERTICAL)
w1.add(w2)

e1 = Entry(w2)
e2 = Entry(w2)

w2.add(e1)
w2.add(e2)
bottomBtn = Button(w2, text="Addition", command=addition)
w2.add(bottomBtn)

mainloop()

As you can see above, in the output, we have an application window, in


which we have 3 tkinter Entry widgets and 1 tkinter button widget, stacked
using 2 PanedWindow widgets packed vertically besides each other.
If you will provide, two numbers in the right side entry widgets and then
click on the Addition button, the result of addition of the numbers in the
right, will be shown in the entry widget on the left hand side.

TKINTER PANEDWINDOW WIDGET - MULTIPLE PANES EXAMPLE


Let us see another code snippet of this widget given below:
from tkinter import *
from tkinter import tk
win = Tk()

pw = PanedWindow(orient ='vertical')
#creating Button widget
top = tk.Button(pw, text ="Just Click Me!!!\nI am a Button")
top.pack(side=TOP)
#Adding button widget to the panedwindow
pw.add(top)
#Creating Checkbutton Widget
bot = Checkbutton(pw, text="I am Checkbutton Choose Me!")
bot.pack(side=TOP)
pw.add(bot)

label = Label(pw, text="I am a Label")


label.pack(side=TOP)
pw.add(label)

string = StringVar()
entry = Entry(pw, textvariable=string, font=('arial', 15, 'bold'))
entry.pack()

# This is used to force focus on particular widget


# that means widget is already selected for some operations
entry.focus_force()
pw.add(entry)
pw.pack(fill = BOTH, expand = True)

# To show sash
pw.configure(sashrelief = RAISED)
mainloop()

In the above code example, we have create multiple widgets inside a


panedwindow widget. We have also used StringVar() variable and we have
used the focus_force() function to have entry widget in focus when the
application is loaded.

Python Tkinter LabelFrame Widget


In this tutorial, we will cover the Tkinter LabelFrame widget in Python with
its syntax and few examples. The LabelFrame widget is mainly used to draw
borders around the child widgets.
This widget is a bordered container widget and is used to group the
related widgets in a Tkinter application to provide a better user
experience to the user.
For example, we can group the radiobutton widgets used in an
application using the labelframe widget.
One can also add a title for the LabelFrame widget(we will see this in
the code example).
The LabelFrame widget is simply a variant of the Frame widget and
it has all the features of a frame.
Note: If you have used HTML for web development, then the labelframe is
just like HTML fieldset tag.

TKINTER LABELFRAME WIDGET


The syntax of the LabelFrame widget is given below. Let us see
w = LabelFrame(master, option=value)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure the labelframe and these options are written
as comma-separated key-value pairs.

TKINTER LABELFRAME WIDGET OPTIONS:


Following are the various options used with LabelFrame widgets:

Name of the
Description
Option

height
This option is used to represent
the height of the widget.

width
This option is used to represent
the width of the frame.

This option represents the string


text containing the text of the
Label.

This option represents the style


relief of the border.The default value
of this option is GROOVE

This option represents the


padx horizontal padding of the
widget

pady
This option represents the
vertical padding of the widget

font
This option represents the font
type of the text of the widget

highlighthickness
This option represents the width
of the focus highlight border

This option indicates the color of


highlightbackground
the focus highlight border at
the time when the widget doesn't
have the focus
This option indicates the color of
highlightcolor the focus highlight when the
widget is under the focus

bg
This option indicates the
background color of the widget

This option is used to represent


bd
the size of the border around
the indicator.The default value
of this option is 2 pixels.

Class
The default value of this option
is LabelFrame.

This option is mainly used to


specify which colomap to be
used for this widget.With the
colormap
help of this option, we can reuse
the colormap of another window
on this widget.The colormap
means 256 colors that are used
to form the graphics

The LabelFrame becomes the


container widget if we will set
container the value of this option to
true.The default value of this
option is false

This option will convert the


cursor mouse pointer to the specified
cursor type and it can be set to
an arrow, dot, etc

This option is used to indicate


fg the foreground color of the
widget

This option represents the exact


labelAnchor
position of the text inside the
widget. The default value of this
option is NW(north-west)

This option indicates the widget


to be used for the label.
labelwidget Also,the frame uses the text
for the label if no value
specified

TKINTER LABELFRAME WIDGET EXAMPLE


Below we have a basic example of the LabelFrame widget. Let us see the
code snippet given below:
from tkinter import *

win = Tk()
win.geometry("300x200")
labelframe1 = LabelFrame(win, text="Happy Thoughts!!!")
labelframe1.pack(fill="both", expand="yes")

toplabel = Label(labelframe1, text="You can put your happy thoughts here")


toplabel.pack()
labelframe2 = LabelFrame(win, text = "Changes You want!!")
labelframe2.pack(fill="both", expand = "yes")

bottomlabel = Label(labelframe2, text = "You can put here the changes you want,If any!")
bottomlabel.pack()
win.mainloop()

As you can see in the output above, we have created two labelframe widgets,
in which we have added text for the labelframe widgets, and inside the
labelframe widget we have one label widget. We can have as many widgets
inside the labelframe widget, as we want.

Python Tkinter MessageBox


In this tutorial, we will cover how to create and use Tkinter
MessageBox while developing desktop applications.
In order to display message boxes in a desktop application, we use the
MessageBox module in Tkinter.
There are various functions present in this module which helps
to provide an appropriate type of message according to the
requirement.
With the help of this module, we can create pop-up message boxes to
take user input.
The functions of the MessageBox module are as
follows: showError() , askretrycancel() , showwarning() , etc., all of which are
used to create a messagebox.

TKINTER MESSAGEBOX
To use the messagebox module, we first need to import it in our python
script:
from tkinter import messagebox
Then following is the basic syntax to use the messagebox:
messagebox.function_name(title, message [, options])
In the above syntax, we have used the following:
function_name
This is used to indicate the name of the appropriate MessageBox
Function.
title
This is used to indicate the text to be displayed in the title bar of the
appropriate message box.
message
This is used to indicate the text to be displayed as a message in the
message box.
options
It is used to indicate various options in order to configure the
MessageBox. There are two values of it and these
are default and parent.
default: It is used to specify a default button such as ABORT,
RETRY, IGNORE.

parent: It is used to specify a window on the top of which we


will display the MessageBox.
The functions present in the MessageBox module uses the same syntax but
the functionalities of each function are different.
Let us see a few functions of the Tkinter MessageBox module.
TKINTER MESSAGEBOX - SHOWWARNING()

This method is used to display any warning to the user in a Python


application.
Here is a code for the same:
from tkinter import *

from tkinter import messagebox


win = Tk()
win.geometry("200x200")
messagebox.showwarning("warning","This is a Warning")

win.mainloop()

TKINTER MESSAGEBOX - ASKQUESTION()

This method in MessageBox is mainly used to ask some question to the


user which can be answered either in Yes or No.
The code for this method is as follows:
from tkinter import *
from tkinter import messagebox

win = Tk()
win.geometry("100x100")
messagebox.askquestion("Confirm","Are you sure about it?")
win.mainloop()
TKINTER MESSAGEBOX - ASKRETRYCANCEL()

If you want to ask a user to do any particular task or not then this method
will be used.
Let us see the code for the same:
from tkinter import *
from tkinter import messagebox
win= Tk()
win.geometry("100x100")
messagebox.askretrycancel("Application"," wanna try again?")

win.mainloop()
TKINTER MESSAGEBOX - SHOWERROR()

To display an error message this method will be used.


Let us see the code snippet given below:
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.showerror("errorWindow","oops!!!Error")
top.mainloop()
In this tutorial, we will cover the Tkinter Listbox widget in Python which is
used to display different types of items to the user in form of a List inside a
box and the user can select the items.
The items contain the same type of font and the same font color.
It is important to note here that only text items can be placed inside
a Listbox widget.
From this list of items, the user can select one or more items according
to the requirements.
Tkinter Listbox Widget
The syntax of the Tkinter Listbox widget is given below:
W = Listbox(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the ListBox and these options are
written as comma-separated key-value pairs.
Tkinter Listbox Widget Options:
Following are the various options used with Listbox widgets:

Name of
Description
Option
bg This option indicates the background color of the widget.

bd
This option is used to represent the size of the border. The
default value is 2 pixels.

cursor
With the help of this option, the mouse pointer will
look like the cursor type like dot, arrow, etc.

font This option indicates the font type of the Listbox items.

fg This option indicates the color of the text.

This option is used to represents the count of the


height lines shown in the Listbox. The default value of this option
is 10.

highlightcolor
This option is used to indicate the color of the Listbox
items when the widget is under focus.

highlightthickness
This option is used to indicate the thickness of the
highlight.

relief
This option indicates the type of border. The default value
is SUNKEN.
selectbackground This option is used to indicate the background color that is
used to display the selected text.

This option is used to determine the number of items that


selectmode can be selected from the list. It can set
to BROWSE, SINGLE, MULTIPLE, EXTENDED.

width
This option is used to represent the width of the widget in
characters.

xscrollcommand
This option is used to let the user scroll the Listbox
horizontally.

yscrollcommand
This option is used to let the user scroll the Listbox
vertically.

Tkinter ListBox Widget Methods:


Following are the methods associated with the Listbox widget:

Method Description

This method is
activate(index)
mainly used to
select the lines at
the specified index.

This method is
used to return a
tuple containing the
line numbers of the
curselection() selected element or
elements, counting
from 0. If nothing
is selected, return
an empty tuple.

This method is
delete(first, last = None)
used to delete the
lines which exist in
the given range.

This method is
get(first, last = None)
used to get the list
of items that exist
in the given range.

This method is
used to place the
index(i)
line with the
specified index at
the top of the
widget.

This method is
used to insert the
insert(index, *elements)
new lines with the
specified number of
elements before the
specified index.

This method is
used to return the
nearest(y) index of the nearest
line to the y
coordinate of the
Listbox widget.

This method is
used to adjust the
see(index)
position of the
Listbox to make the
lines specified by
the index visible.

This method
returns the number
size() of lines that are
present in the
Listbox widget.

This method is
xview()
used to make the
widget horizontally
scrollable.

This method is
used to make the
Listbox
horizontally
xview_moveto(fraction) scrollable by the
fraction of the
width of the longest
line present in the
Listbox.
This method is
used to make the
listbox horizontally
xview_scroll(number, what) scrollable by the
number of
characters
specified.

This method allows


yview()
the Listbox to be
vertically
scrollable.

This method is
used to make the
listbox vertically
yview_moveto(fraction)
scrollable by the
fraction of the
width of the longest
line present in the
Listbox.

This method is
used to make the
listbox vertically
yview_scroll (number, what) scrollable by the
number of
characters
specified.

Tkinter ListBox Widget Example


Below we have a basic example using this widget:
from tkinter import * top = Tk() top.geometry("200x250") lbl = Label(top, text="List of Programming
Languages") listbox = Listbox(top) listbox.insert(1,"Python") listbox.insert(2, "Java") listbox.insert(3,
"C") listbox.insert(4, "C++") lbl.pack() listbox.pack() top.mainloop()

In the code example above, we have created a simple Listbox widget with
some items along with specifying the top list item which is the heading on the
Listbox widget.

Python Tkinter Menu Widget


In this tutorial, we will cover the Tkinter Menu widget in Python which is
used to create Menus with options for users to choose from.
The Tkinter Menu widget is used to create different types of menus in Python
Application.
The following types of menus can be created using the Tkinter Menu
widget: pop-up, pull-down, and top level.
Top-level menus are those menus that are displayed just under the title
bar of the root or any other top-level windows. For example, all the
websites have a top navigation menu just below the URL bar in the
browser.
Menus are commonly used to provide convenient access to options
like opening any file, quitting any task, and manipulating data in an
application.
Tkinter Menu Widget
The syntax of the Menu widget is given below:
W = Menu(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the menu and these options are
written as comma-separated key-value pairs.
Tkinter Menu Widget Options:
Following are the various options used with Menu widgets:

Name of
the Description
Option

activebackground
This option is used to indicate the background color of the
widget when the widget is under the focus.

activeforeground
This option indicates the font color of text of the widget
when the widget has the focus.

This option is used to indicate the width of the border of


activeborderwidth the widget when it is under the mouse(when it is active).
The default value of this option is 1 pixel.

bd
This option is used to indicate the border width of the
widget

bg This option indicates the background color of the widget.

cursor
This option indicates the cursor when the mouse hovers
the menu.

disabledforeground
This option indicates the text color of the widget when
the widget is disabled

font
This option is used to indicate the font type of the text of
widget

fg This option specifies the foreground color of the widget.

relief
This option is used to specify the border type. Its default
value is RAISED.

image This option is used to display an image on the menu

postcommand
This option can be set to any of the function which is
called when the mouse hovers the menu.
The choices in the menu start from position 1 by default.
tearoff
But If we set the tearoff=1 , then choices will start taking
place from 0th position.

selectcolor
This option indicates the color used to display the
checkbutton or radiobutton when they are selected.

title
This option is set to the title of the window if you want to
change the title of the window.

Tkinter Menu Widget Methods:


Following are the various methods used with Tkinter Menu widget:

Name of method Description

add_command()
This method is used to add menu
items to the menu.

add_radiobutton()
This method is used to add
the radiobutton to the menu.

add_checkbutton()
This method is mainly used
to add checkbuttons to the menu.

This method is used to create a


add_cascade()
hierarchical menu to the parent
menu by associating the given
menu to the parent menu.
add_seperator()
This method is used to add the
separator line to the menu items.

add(type, options)
This method is used to add the
specific menu item to the menu.

This method is used to delete the


delete(startindex, endindex) menu items that exist in the
specified range.

This method is used to configure a


entryconfig(index, options) menu item that is identified by the
given index.

index(item)
This method is used to get the
index of the specified menu item.

insert_seperator(index)
This method is used to insert a
separator at the specified index.

This method is used to invoke the


invoke(index)
associated operation with the
choice given at the specified
index.

This method is used to get the


type(index) type of choice specified by the
index.
As you can see above we have so many methods associated to the Menu
widget which can be used to configure the menu as per your requirement.
Tkinter Menu Widget Example
Below we have a basic example using this widget:
from tkinter import * root = Tk() def hello(): print("hello!") menubar = Menu(root)
menubar.add_command(label="Hello StudyTonight!", command=hello)
menubar.add_command(label="Quit!", command=root.quit) root.config(menu=menubar)
root.mainloop()

After running the above code, you will see the above output. Whenever you
will click on Hello StudyTonight! menu item then it will print a hello! on
your console. While on clicking the Quit! menu item, the application will
close.
Python Tkinter Menubutton Widget
In this tutorial, we will cover the Tkinter Menubutton widget in Python which
is used to create a dropdown menu which can be clicked by the user to see
the
This widget is used to provide various types of menus in the Python
Application.
It is important to note that every Menubutton in an application is
associated with a Menu widget and that in return can display the choices
for that menubutton whenever the user clicks on it.
The Tkinter Menubutton widget provides the user with an option to
select the appropriate choice that exists within the application.
Tkinter Menubutton Widget
The syntax of the Tkinter Menubutton widget is given below:
W = Menubutton(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the menubuttons and these options
are written as comma-separated key-value pairs.
Tkinter Menubutton Widget Options:
Following are the various options used with Tkinter Menubutton widgets:

Option name Description

This option indicates the


background color of the
activebackground menubutton at the
time when the mouse
hovers the menubutton.

This option is used


bd
to represent the width of
the border in pixels. The
default value is 2 pixels.
This option will be set to
bitmap
the graphical
content which is to be
displayed to the widget.

This option is used


bg
to represent the
background color of the
widget.

This option indicates the


cursor cursor when the mouse
hovers the menubutton.

This option
mainly represents the
activeforeground font color of the widget
at the time when the
widget is under the focus

This option represents


fg the foreground color of
the widget.

With the help of this


option, you can specify
the direction so that
menu can be displayed to
direction the specified direction of
the button. You can
Use LEFT, RIGHT, or
ABOVE to place the
widget accordingly.

This option indicates


disabledforeground
the text color of the
widget when the widget
is disabled

This option indicates the


height of the
menubutton. This height
indicates the number of
height text lines in the case
of text lines and it
indicates the number of
pixels in the case of
images.

This option indicates the


image image displayed on the
menubutton.

This option indicates the


higlightcolor
highlight color when
there is a focus on the
button

This option is used to


indicate the way by
which the multiple text
lines are represented. For
justify left justification, it is set
to LEFT and it is set to
RIGHT for the right
justification, and
CENTER for the center
justification.

This option indicates the


padx
additional padding of the
widget in the horizontal
direction.

This option indicates the


pady
additional padding of the
widget in the vertical
direction.

This option is used


menu
to indicate the menu
associated with the
menubutton

This option specifies the


width of the widget. For
width
textual buttons, It exists
as a number of letters or
for image buttons it
indicates the pixels

In this case, if this


option's value is set to a
positive number, the text
Wraplength lines will be wrapped in
order to fit within this
length.

As the normal state


of menubutton is
state
enabled.It can be set to
disable to make the
menubutton
unresponsive.

This option is used to


text indicate the text on the
widget.

A control variable of
class StringVar can be
associated with this
textvariable
menubutton. If you
will set that control
variable then it will
change the displayed
text.

This option is mainly


used to represent the
index of the character in
underline
the text of the widget
which is to be
underlined. The indexing
generally starts with zero
in the text.
This option is used
relief
to specify the border
type. Its default value is
RAISED

Tkinter Menubutton Widget Example


Now let us see a code snippet for the Tkinter Menubutton widget:
from tkinter import * import tkinter win = Tk() mbtn = Menubutton(win, text="Courses",
relief=RAISED) mbtn.grid() mbtn.menu = Menu(mbtn, tearoff = 0) mbtn["menu"] = mbtn.menu
pythonVar = IntVar() javaVar = IntVar() phpVar = IntVar()
mbtn.menu.add_checkbutton(label="Python", variable=pythonVar)
mbtn.menu.add_checkbutton(label="Java", variable=javaVar)
mbtn.menu.add_checkbutton(label="PHP", variable=phpVar) mbtn.pack() win.mainloop()
The output of the above code is as follows:

You can try the above example by yourself. Whenever you will execute the
above code, you will see there is a Tkinter menubutton named Courses on a
window whenever you will click on it then it will show you a drop-down
menu like this:

Summary:
In this tutorial, we covered the Tkinter Menubutton widget which is used to
create drop-down menus in a Tkinter application.

Python Tkinter Message Widget


In this tutorial, we will learn about the Tkinter Message widget in Python
which is used to show some text message on the GUI application that you
create using Tkinter.
The Tkinter Message Widget in Python is mainly used to show some
message to the user who is using the application.
The message displayed by the Tkinter Message Widget is of non-
editable type and it can be in multiline.
The message displayed by the Tkinter Message widget contains single
font text.
The functionality of this widget is very similar to the Tkinter Label
widget, but there is a difference and that is the message widget
can automatically wrap the text.
Tkinter Message Widget
The syntax of the Tkinter Message widget is given below:
W = Message(master,options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the message and these options are
written as comma-separated key-value pair.
Tkinter Message Widget Options:
Following are the various options used with the Tkinter Message widget:

Name of the option Description

It is mainly used to decide the exact


anchor
position of the text within the
provided space. The default value
of this option is CENTER.
bg This option denotes the background
color of the widget.

This option is used to indicate the


bd border width of the widget. The
default value of this is 2 pixels.

In order to display graphics on the


bitmap
widget, this option will be used.
You can set it to any graphical or
image object.

With the help of this option, the


cursor
mouse pointer will be changed to a
specific cursor type like an arrow,
dot, etc.

fg
This option is used to indicate the
font color of the widget text.

font
This option is used to indicate the
font type of the widget text.

This option is used to indicate the


height vertical dimension of the message
widget.

image
This option is used to indicate the
image on the widget.
This option is used for
justify
the justification of the text on the
widget. It can be CENTER, LEFT,
RIGHT

This option is used for


padx the horizontal padding of the
widget.

pady
This option is used for the vertical
padding of the widget.

This option is used to specify the


relief border type. Its default value is
FLAT

This option can be set to an existing


number in order to specify that nth
underline letter of the string will be
underlined. Its default value
is -1 which indicates no underline.

If you want to display one or more


lines of text in a label widget you
text
need to set this option to a string
containing the text. You can use
"\n" just in order to enter multiple
lines
This option is used to control the
text represented by the widget.
textvariable
The textvariable can be set to the text
that is needed to be shown on the
widget.

This option is used to indicate the


width
horizontal dimension of the widget
in the number of characters and not
in pixels.

This option is used to wrap the


text to the number of lines just by
wraplength setting this option to the desired
number so that each line contains
only that number of characters.

Tkinter Message Widget Example


Below we have a basic example for the Tkinter Message widget:
from tkinter import * win = Tk() win.geometry("300x200") w = Label(win, text ='StudyTonight', font =
"90",fg="Navyblue") w.pack() msg = Message(win, text = "Best place to learn coding online")
msg.pack() win.mainloop()
In the code example above, we have created a simple label widget and a
message widget with some text message in it.

Python Tkinter Radiobutton Widget


In this tutorial, we will cover the Tkinter Radiobutton widget in Python,
which is used when we want to add a radio button to the GUI of our
application.
Tkinter radiobutton widget is used to implement multiple-choice options that
are mainly created in user input forms.
This widget offers multiple selections to the user and allows the user to
select only one option from the given ones. Thus it is also known as
implementing one-of-many selection in a Python Application.
Also, different methods can also be associated with radiobutton.
You can also display multiple line text and images on the radiobutton.
Each radiobutton displays a single value for a particular variable.
You can also keep a track of the user's selection of the
radiobutton because it is associated with a single variable
Tkinter Radiobutton Widget
The syntax of the Radiobutton widget is given below:
W = Radiobutton(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the radiobutton and these options
are written as comma-separated key-value pairs.
Tkinter Radiobutton Widget Options:
Following are the options used with Tkinter Radiobutton widgets:

Name of the option Description

This option is used to represent


the exact position of the
text within the widget, in the
anchor case of the widget contains more
space than the requirement of
the text. The default value of
this option is CENTER.

bg
This option represents the
background color of the widget.

This option represents the


activebackground background color of the
widget when it is under focus.

This option represents the font


activeforeground color of the widget when it is
under focus.

borderwidth
This option is used to represent
the size of the border.

If you want to display graphics


bitmap
on the widget then you can set
this widget to any graphical or
image object.

This option is used to set the


command
procedure which must be called
every time when the state of the
radiobutton is changed.

This option will convert the


cursor
mouse pointer to the specified
cursor type and it can be set to
an arrow, dot, etc.

This option is used to represent


font the font type of the text of the
widget.

This option is used to represent


fg the foreground color of the text
of the widget.
height
This option indicates the vertical
dimension of the widget

This option indicates


width
the horizontal dimension of the
widget and it is represented as
the number of characters.

This option represents the


padx horizontal padding of the
widget.

pady
This option represents the
vertical padding of the widget

This option is used to represent


highlightcolor
the color of the focus
highlight when the widget is
under the focus

This option is used to represent


highlightbackground
the color of the focus
highlight when the widget is not
under the focus.

If you want to display an image


image
on the widget then this option
will be set to an image rather
than the text
This option is used to represent
the justification of the multiline
justify text. The default value
is CENTER. Other values
are LEFT, RIGHT.

This option is used to represent


relief the type of border. The default
value is FLAT.

This option indicates the color


selectcolor of the radiobutton when it is
selected

This option indicates the image


selectimage to be displayed on the
radiobutton when it is selected

This option is used to represent


the state of the radio button. The
default state of the Radiobutton
state is NORMAL. You can also set
the state to DISABLED in order
to make the radiobutton
unresponsive.

text
This option indicates the text to
be displayed on the radiobutton.

This option is used to control


the text represented by the
textvariable widget. The textvariable can
be set to the text that is needed
to be shown on the widget.

This option can be set to an


existing number in order to
underline
specify that nth letter of the
string will be underlined. Its
default value is -1 which
indicates no underline

This option is also known as


the control variable which is
variable used to keep the track of user's
choices. Thus this variable is
shared among all radiobuttons.

This option of each radiobutton


value
is assigned to the control
variable when it is turned on by
the user.

This option is used to wrap the


text to the number of lines just
wraplength
by setting this option to the
desired number so that each line
contains only that number of
characters.

Tkinter Radiobutton Widget Methods:


Following are the various methods used with the Tkinter Radiobutton
widgets:

Method
Description
Name

deselect()
This method is used to deselect or turns
off the radio button

select()
This method is used to select the radio
button

This method is generally used to call a


invoke() function when the state of radio button
gets changed.

This method is generally used to flash the


flash() radio button between its normal and active
colors many times.

Tkinter Radiobutton Widget Example


Below we have a basic example for the radio button widget. let us see the
code snippet for the Radiobutton widget:
#firstly ImportTkinter module
from tkinter import *
from tkinter.ttk import *
# Creating parent Tkinter window
win = Tk()
win.geometry("200x200")

# let us create a Tkinter string variable


# that is able to store any string value
v = StringVar(win, "1")
# here is a Dictionary to create multiple buttons
options = {" Option A" : "1",
"Option B" : "2",
"Option C" : "3",
"Option D" : "4"
}
# We will use a Loop just to create multiple
# Radiobuttons instaed of creating each button separately
for (txt, val) in options.items():
Radiobutton(win, text=txt, variable=v, value=val).pack(side = TOP, ipady = 4)

mainloop()
The above code will give the following output:

Note: If you will try above code snippet by yourself then you will see that in
the output you can select only one button at a time.

TKINTER RADIOBUTTON WIDGET ANOTHER EXAMPLE


Below we have another example of this widget where we will add styling to
radiobutton using style class:
from tkinter import *
from tkinter.ttk import *

win= Tk()
win.geometry('200x200')
v = StringVar(win, "1")
# we will add Style class to add style to Radiobutton
style = Style(win)
style.configure("TRadiobutton", background = "light blue",
foreground = "orange", font = ("arial", 14, "bold"))

# Dictionary to create multiple buttons


values = {"RadioButton 1" : "1",
"RadioButton 2" : "2",
"RadioButton 3" : "3"
}
for (text, value) in values.items():
Radiobutton(win, text = text, variable = v,
value = value).pack(side = TOP, ipady = 3)
mainloop()
The above code will change the font style as well as background and
foreground colors. In the above TRadiobutton is used in style class, which
automatically applies styling to all the available Radiobuttons.

Python Tkinter Scale Widget


In this tutorial, we will cover the Tkinter Scale widget in Python which is
used to add a graphical slider object which the user can slide and choose a
number, as a numeric value is attached to this slider scale and as you move
the slider up/down or right/left the numeric value attached to it increases or
decreases and you can set the slider to the value you wish to select.
The sliding bar provided by the scale widget is helpful in selecting the
values just by sliding from left to right or top to bottom depending
upon the orientation of the sliding bar in our application.
The scale widget is used as an alternative to the Entry widget if the
purpose of the Entry widget is to take numeric input from user within a
given range of values.
You can also control minimum and maximum values along with the
resolution of the scale.

TKINTER SCALE WIDGET


The syntax of the Tkinter Scale widget is given below:
W = Scale(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the layout of the scale widget and
these options are written as comma-separated key-values.

TKINTER SCALE WIDGET OPTIONS:


Following are the various options used with Tkinter Scale widget:

Name of
Description
the option

activebackground
This option represents the background color of the
widget when it is under focus.

bg
This option represents the background color of the
widget

bd
This option represents the border size of the widget.
The default value is 2 pixels.

With the help of this option, the mouse pointer will be


cursor changed to a specific cursor type and it can be an
arrow, dot, etc.
This option will be set to the procedure which is
command called every time when we move the slider. If we
move the slider rapidly, the callback to the procedure
is done when it settles.

When the control variable which is used to control the


digits
scale data is of string type, then this option is mainly
used to specify the number of digits when the numeric
scale is converted to a string.

fg This option indicates the foreground color of the text

font This option indicates the font type of the text

from_
This option is used to represent one end of the widget
range.

highlightcolor
This option indicates the highlight color when
the widget is under the focus

highlightbackground
This option indicates the highlight color when
the widget is not under the focus

This option can be set to some text which then can be


shown as a label with the scale. If the scale is
label horizontal then it is shown in the top left corner or if
the scale is vertical then it shown in the top right
corner.

This option indicates the length of the widget. It


length represents the X dimension if the scale is in the
horizontal direction and it represents the Y
dimension if the scale is in a vertical direction.

relief
This option is used to specify the border type. Its
default value is FLAT

orient
This option can be set to either horizontal or vertical
depending upon the type of the scale.

resolution
This option will be set to the smallest change which is
made to the value of the scale

This option is mainly used to tell the duration up to


repeatdelay
which the button is to be pressed before the slider starts
moving in that direction repeatedly. its default value
is 300 ms

This option represents the length of the slider window


sliderlength along the length of the scale. Its default value is 30
pixels. Also, you can change it to the appropriate value.

By default, the value of the scale is shown in the text


showvalue form, also we can set this option to 0 in order to
suppress the label.

state
By default, the state of the scale widget is active. To
make it unresponsive you can also set it to DISABLED

This option is used to represent the width of the trough


width part of the widget

variable
This option is used to represent the control variable
for the scale

This option is used represents a float or integer value


to that specifies the other end of the range represented by
the scale

Generally, the focus will cycle through the scale


takefocus widgets. If you don't want this behavior you can set this
option to 0.

With the help of this option, scale values are displayed


tickinterval on the multiple of the specified tick interval. The
default value of this option is 0.

troughcolor This option is used to set the color for the trough

TKINTER SCALE WIDGET METHODS


Following are the few methods used with Scale widgets:
get() :
This method is used to get the current value of the scale.

set(value) :

This method is used to set the value of the scale.

TKINTER SCALE WIDGET - HORIZONTAL EXAMPLE


Below we have a basic example where we will create a horizontal slide bar.
from tkinter import *
win = Tk()
win.geometry("200x100")

v = DoubleVar()
scale = Scale( win, variable=v, from_=1, to=50, orient=HORIZONTAL)
scale.pack(anchor=CENTER)

btn = Button(win, text="Value")


btn.pack(anchor=CENTER)
label = Label(win)
label.pack()

win.mainloop()

In this tutorial, we have created a horizontal Scale widget. If you see in the
code, we have specified the orient as HORIZONTAL for this. We have also
specified the range of numeric values for the slider scale.

TKINTER SCALE WIDGET - VERTICAL EXAMPLE


Below we have another example where we will create a vertical slider:
from tkinter import *
win = Tk()
win.geometry("400x300")

v = DoubleVar()
def show():
sel = "The Vertical Scale Value is = " + str(v.get())
# adding scale value to label to show
scale_val.config(text=sel, font=("Courier", 16))
scl = Scale(win, variable=v, from_=60, to=1, orient=VERTICAL)

mainlabel = Label(win, text="The Vertical Slider")


btn = Button(win, text ="Show Slider Value",
command = show,
bg = "darkblue",
fg = "white")

# creating another label to show the scale value


scale_val = Label(win)
scl.pack(anchor = CENTER)
mainlabel.pack()
btn.pack()
scale_val.pack()

win.mainloop()

You can move the slider from bottom to top as it is a vertical slider. In the
given example, we have also added a button to our application, and we
have defined a function show() that is attached to the button widget as
an event handler. So after the user uses the slider to select any value, and
then clicks on the button, the value will be displayed in a Label widget below
the button.

Python Tkinter Scrollbar Widget


In this tutorial, we will cover the Tkinter Scrollbar widget in Python, using
which we can add a scrollbar to the user interface of our Tkinter application.
To scroll up or down or right or left the content in a Python desktop
application, the Tkinter Scrollbar widget is used.
To scroll the content of other widgets like Listbox, canvas, etc we use
this widget.
Both Horizontal and Vertical scrollbars can be created in the Trinket
Entry widget.
Below we have an image showing scrollbar widget used with a Listbox:
TKINTER SCROLLBAR WIDGET
The syntax of the Scrollbar widget is given below:
W = Scrollbar(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure your scrollbar widget and
these options are written as comma-separated key-value pairs.
Tkinter Scrollbar Widget Options:
Following are the various options used with Tkinter Scrollbar widgets:
Name of Description
the Option

activebackground
This option represents the background color of the
widget when it is under focus.

bg
This option represents the background color of the
widget

bd
This option represents the border size of the widget.
The default value is 2 pixels.

With the help of this option, the mouse pointer will be


cursor changed to a specific cursor type and it can be an
arrow, dot, etc.

command
This option will be set to the procedure associated
which is called every time the scrollbar is moved.

This option mainly represents the border width around


elementborderwidth the arrowheads and the slider. The default value of this
option is -1.

highlightthickness
This option represents the thickness of the focus
highlights

highlightbackground
This option indicates the highlight color when
the widget is not under the focus
highlightcolor This option indicates the highlight color when
the widget is under the focus

This option is used to control the behavior of the scroll


jump jump. If this option is set to 1, then the callback is called
at the time when the user releases the mouse button.

orient
This option can be set to either horizontal or vertical
depending upon the orientation of the scrollbar.

width This option represents the width of the scrollbar.

troughcolor This option is used to set the color for the trough

By default, you can tab the focus through this widget.


takefocus If you don't want this behavior you can set this option to
0.

This option is mainly used to tell the duration up to


repeatdelay
which the button is to be pressed before the slider starts
moving in that direction repeatedly. its default value
is 300 ms

repeatinterval The default value of this option is 100

Tkinter Scrollbar Widget Methods:


Few methods used with Tkinter Scrollbar widgets are:
get() :
This method returns the two numbers
suppose a and b which represents the current position of the
scrollbar.
set(first, last) :

This method is used to connect the scrollbar to any other widget.


That is yscrollcommand or xscrollcommand of the other widget to this
method.

TKINTER SCROLLBAR WIDGET EXAMPLE


Below we have a basic example of a scrollbar widget.
from tkinter import *

win= Tk()
sbb = Scrollbar(win)
sbb.pack(side = RIGHT, fill = Y)

mylist = Listbox(win, yscrollcommand = sbb.set)


for line in range(45):
mylist.insert(END, "Value " + str(line))

mylist.pack(side = LEFT)
sbb.config(command = mylist.yview)
mainloop()
As you can see in the above code, we have created a Listbox widget with
numbers as list items in it. Then we have created a Scrollbar widget and have
used the yscrollcommand option of the Listbox widget to set the Scrollbar
widget with it. We have used the Scrollbar widget's set function here.

Python Tkinter Text Widget


In this tutorial, we will cover the Tkinter Text widget in Python. If you want
a text-editor in your desktop application then you can use the Tkinter Text
widget.
The text widget is used to provide a multiline textbox (input box)
because in Tkinter single-line textbox is provided using Entry widget.
You can use various styles and attributes with the Text widget.
You can also use marks and tabs in the Text widget to locate the
specific sections of the text.
Media files like images and links can also be inserted in the Text
Widget.
There are some variety of applications where you need multiline text
like sending messages or taking long inputs from users, or to show
editable long format text content in application, etc. use cases are
fulfilled by this widget.
Thus in order to show textual information, we will use the Text widget.

TKINTER TEXT WIDGET


The syntax of the Text widget is given below:
W = Text(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure the text editor and these options are written
as comma-separated key-value pairs.

TKINTER TEXT WIDGET OPTIONS:


Following are the various options used with Text widgets:

Name of
Description
the option

bd This option represents the border width of the widget.

bg
This option indicates the background color of the
widget.

This option is used to export the selected text in the


exportselection
selection of the window manager. If you do not want to
export the text then you can set the value of this option
to 0.

This option will convert the mouse pointer to the


cursor specified cursor type and it can be set to an arrow, dot,
etc.

font This option is used to indicate the font type of the text.

fg This option indicates the text color of the widget

height
This option indicates the vertical dimension of the
widget and it is mainly in the number of lines.

highlightbackground
This option indicates the highlightcolor at the time
when the widget isn't under the focus.

higlightthickness
This option is used to indicate the thickness of the
highlight. The default value of this option is 1.

highlightcolor
This option indicates the color of the focus
highlight when the widget is under the focus.

insertbackground
This option is used to represent the color of the
insertion cursor.

padx
This option indicates the horizontal padding of the
widget.

pady
This option indicates the vertical padding of the
widget.

This option indicates the type of the border of the


relief
widget. The default value of this option is SUNKEN.

If the value of this option is set to DISABLED then


state the widget becomes unresponsive to mouse and
keyboard

tabs
This option is used to control how the tab character is
used for the positioning of the text

width
This option represents the width of the widget and this
is in characters.

To wrap wider lines into multiple lines this option is


wrap
used. The default value of this option
is CHAR which breaks the line which gets too wider
at any character

If you want to make the Text widget horizontally


xscrollcommand scrollable, then you can set this option to
the set() method of Scrollbar widget

If you want to make the Text widget vertically


yscrollcommand scrollable, then you can set this option to
the set() method of Scrollbar widget

spacing1
This option indicates the vertical space to insert above
each line of the text.

This option is used to specify how much extra vertical


spacing2 space to add between displayed lines of text when a
logical line wraps. The default value of this option is 0

spacing3
This option indicates the vertical space to insert below
each line of the text.

selectbackground
This option indicates the background color of the
selected text.

selectborderwidth
This option indicates the width of the border around
the selected text.

This option represents the time amount in


insertofftime Milliseconds and during this time the insertion
cursor is off in the blink cycle

This option represents the time amount in


insertontime Milliseconds and during this time the insertion
cursor is on in the blink cycle

In order to represent the width of the border around


insertborderwidth the cursor, we use this option. The default value of this
option is 0.

TKINTER TEXT WIDGET METHODS:


Some methods used with the text widget are given below:

Method Description

index(index) This method is used to get the specified index.


see(index)
This method returns true or false on the basis that if
the string is visible or not at the specified index.

insert(index,string)
This method is used to insert a string at the specified
index.

get(startindex,endindex)
This method returns the characters in the specified
range

delete(startindex,endindex)
This method deletes the characters in the specified
range

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:
tag_config()
To configure the properties of the tag this method will be used.
tag_add(tagname, startindex, endindex)
This method is mainly used to tag the string that is present at the
specified index.
tag_delete(tagname)
This method is mainly used to delete the specified tag.
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:
index(mark)
This method is mainly used to get the index of the mark specified.
mark_names()
This method is used to get all the names of the mark in the range in
the text widget.
mark_gravity(mark, gravity)
To get the gravity of the given mark this method will be used.
mark_set(mark, index)
This method is used to inform the new position of the given mark.
mark_unset(mark)
In order to remove the given mark from the text this method will be
used.

TKINTER TEXT WIDGET EXAMPLE


Let us discuss a basic example for the text widget. The code snippet for the
example of the text widget is given below:
import tkinter as tk
from tkinter import *
win = Tk()

#to specify size of window.


win.geometry("250x170")
# To Create a text widget and specify size.
T = Text(win, height = 6, width = 53)

# TO Create label
l = Label(win, text = "Quote for the Day")
l.config(font =("Courier", 14))
Quote = """Success usually comes to those who are too busy to be looking for it"""

# Create a button for the next text.


b1 = Button(win, text = "Next", )
# Create an Exit button.
b2 = Button(win, text = "Exit",
command = win.destroy)

l.pack()
T.pack()
b1.pack()
b2.pack()
# Insert the Quote
T.insert(tk.END, Quote)
tk.mainloop()
The output for the code snippet given above is as follows:

If you want to destroy this window just click on the Exit button.

Python Tkinter Toplevel Widget


In this tutorial, we will cover the Tkinter Toplevel widget in Python which is
used to create and display top-level windows other than the application
window.
With the help of the Tkinter Toplevel widget, you can provide extra
information to the user in a separate window on top of the parent
window.
This top-level window created using the Toplevel widget is directly
organized and managed by the window manager.
It is not necessary for the top-level windows to have parents on their
top.
You can create multiple top-level windows one over the other.
Top-level windows created using Top-level widgets contain title bars,
borders, and some window decorations too.
With the help of this widget, you can provide pop-ups, some extra
information, or some widgets on the new window if you want.

PYTHON TKINTER TOPLEVEL WIDGET


The syntax of the Tkinter Toplevel widget is given below:
W = Toplevel(master,options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure your Toplevel widget and
these options are written as comma-separated key-value pairs.

TKINTER TOPLEVEL WIDGET OPTIONS:


Following are the various options used with Tkinter Toplevel widgets are
given below:

Name
of
Description
the
option

bd To represent the border size of the window

bg To represent the background color of the window

Generally, the text selected in the text widget is simply


exported to be selected to the window manager. You can also
class_
set the value of this option to 0 to make this kind of behavior
false.

cursor
This option will convert the mouse pointer to the specified
cursor type and it can be set to an arrow, dot, etc.

width This option is used to represent the width of the window

height This option is used to represent the height of the window

font
This option indicates the font type of the text to be inserted
into the widget.

fg
This option is used to indicate the foreground color of the
widget.

relief This option indicates the type of the window.

TKINTER TOPLEVEL WIDGET METHODS:


Following are the various methods used with Tkinter Toplevel widgets are
given below:

Method Description

title(string)
This method is used to define the title for the
window.

withdraw()
This method is used to delete the window but it
would not destroy the window.
positionfrom(who) This method is used to define the position controller

sizefrom(who) This method is used to define the size controller.

minsize(width,height)
This method is used to declare the minimum size for
the window

maxsize(width,height)
This method is used to declare the maximum size for
the window

resizable(width,height)
This method is used to control whether the
window can be resizable or not.

transient([master])
This method is used to convert the window into a
temporary window

iconify()
This method is used to convert the top-level window
into an icon.

deiconify() This method is mainly used to display the window.

frame()
To indicate a system-dependent window
identifier this method is used.

group(window)
This method is used to add a top-level window to
a specified window group

This method is used to indicate a function which


protocol(name,function) will be called for the specific protocol

This method is used to get the current state of the


state() window. Some Possible values of this option
are normal, iconic, withdrawn, and icon.

TKINTER TOPLEVEL WIDGET EXAMPLE


Below we have a basic example where we will create a simple top-level
window.
from tkinter import *
win = Tk()

win.geometry("200x200")
def open():
top = Toplevel(win)
top.mainloop()

btn = Button(win, text="open", command=open)


btn.place(x=75, y=50)
win.mainloop()
In the code above, we have created a Toplevel widget that is created and
started when the Button is clicked.

Python Tkinter Spinbox Widget


In this tutorial, we will cover Tkinter Spinbox widget in Python with its
syntax and few examples. The Spinbox widget in Tkinter in Python is used
to select a value from the specified given range of values.
It is different from the Tkinter Scale widget (Scale widget being more
stylish) in terms of style, but more or less, fulfils the same purpose.
For example, when you want to have a dropdown of numerical values like
year of birth (from 1950 to 2020) or a dropdown for user to choose their age,
we can use the Tkinter Spinbox widget.
This widget is an alternative to Entry widget, when we want user to
enter a numeric value within a specific range.
This widget is used only in the case where users need to chose from a
given range of choices.
Tkinter Spinbox Widget
The syntax of the Spinbox widget is given below:
w = Spinbox(master, option=value)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure your spinbox widget and
these options are written as comma-separated key-value pairs.
Tkinter Spinbox Widget Options:
Following are the various options used with Tkinter Spinbox widgets:

Name of
the Description
Option

bg
This option is used for the background color of the
widget.

bd This option is used for the border width of the widget

This option is used to indicate the associated


command function with the widget which is called every time the
state of the widget is changed.

With the help of this option, your mouse pointer type


cursor can be changed to the cursor type that is assigned to this
option.

activebackground
This option indicates the background color of the
widget when it is under the focus
disabledbackground
This option is used to indicate the background color of
the widget when it is disabled.

disabledforeground
This option is used to indicate the foreground color of
the widget when it is disabled.

font
This option specifies the font type of text inside the
widget.

fg
This option specifies the foreground color of the
widget.

format
This option is mainly used for the format string. There is
no default value of this option.

from_
This option is used to indicate the starting range of the
widget

This option specifies the alignment of multiple lines in


justify the label. The default value is LEFT. Other values are
RIGHT and CENTER.

relief
This option indicates the type of border. The default
value of this option is SUNKEN.

This option is used to represent the state of the widget.


state The default value of this option is NORMAL. Other
values are "DISABLED", "read-only", etc.
validate
This option is used to control how to validate the value
of the widget

to
This option represents the maximum limit of the widget
value. The other value is specified by the from_ option

repeatdelay
This option is mainly used to control the autorepeat
button. The value here is in milliseconds.

repeatinterval
This option is similar to repeatdelay option. The value
here is also given in milliseconds.

validatecommand
This option is associated with the function callback that
is used for the validation of the content of the widget.

This option is mainly used with the set() method of


xscrollcommand the scrollbar widget to make this widget horizontally
scrollable

wrap
This option is mainly used to wrap-up the up and down
button of the Spinbox

width This option indicates the width of the widget.

vcmd This option is similar to validatecommand.

This option represents the tuple which contains


values the values for the widget
textvariable
It is a control variable that is used to control the text of
the widget

TKINTER SPINBOX WIDGET METHODS:


Following are the various methods used with Tkinter Spinbox widget:

Method
Description
Name

invoke(element)
This method is used to invoke the callback that is
associated with the widget.

insert(index,string)
We use this method mainly to insert the string at the
given specified index

index(index)
To get the absolute value of the given index this method
will be used

identify(x,y)
This method is used to identify the widget's element in
the specified range

get(startindex, This method is used to get the characters in the specified


endindex) range

delete(startindex, This method is used to delete the characters in the


endindex) specified range
TKINTER SPINBOX WIDGET EXAMPLE
Below we have a basic example of the Spinbox widget. Let us see the code
snippet given below:
from tkinter import *

win = Tk()
win.geometry("300x200")
w = Label(win, text ='StudyTonight', fg="navyblue",font = "50")
w.pack()

sp = Spinbox(win, from_= 0, to = 50)


sp.pack()
win.mainloop()

In the above code, we created a simple application window, with a Label


widget and a Spinbox widget with range from 0 to 50.

Python Tkinter PanedWindow


Widget
In this tutorial, we will cover the Tkinter PanedWindow widget which is
mainly a container widget containing one or more than one child
widgets which are also known as Panes.
This widget arranges child widgets either in a vertical or in a horizontal
manner.
It is also known as the Geometry Manager widget.
This widget is used to implement different layouts in a Python desktop
application created using the Tkinter module.
The child widgets inside the PanedWindow widget can be resized by
the user by moving separator lines sashes using the mouse.
You can implement multiple panes using the PanedWindow widget.
Here is a simple Tkinter application window with three widgets stacked
vertically inside a PanedWindow widget.

TKINTER PANEDWINDOW WIDGET


The syntax of the PanedWindow widget is given below:
W = PanedWindow(master, options)
In the above syntax, the master parameter denotes the parent window. You
can use many options to change the look of the PanedWindow and these
options are written as comma-separated.

TKINTER PANEDWINDOW WIDGET OPTIONS:


Following are the various options used with PanedWindow widget:

Name
of
Description
the
Option

This option is used to represent the 3D border size of the


bd
widget. The default value of this option indicates that
the trough contains no border and the arrowheads and
slider contain the 2-pixel border size.

bg This option represents the background color of the widget.

cursor
This option will convert the mouse pointer to the specified
cursor type and it can be set to an arrow, dot, etc.

borderwidth
This option is used to indicate the border width of the
widget. The default value of this option is 2 pixels.

To represents the distance between the handle and the end of


handlepad
the sash we use this option. In horizontal orientation, it is
the distance between the top of the sash and the handle. The
default value of this option is 8 pixels
This option represents the height of the widget. If we do not
height specify the height then the height will be calculated by the
height of the child widgets.

handlesize
This option represents the size of the handle and its default
value is 8 pixels. Also, the handle will always be in square

The value of this option will be set to HORIZONTAL if we


orient
want to place the child windows side by side. If we want to
place the child windows from top to bottom then the value
of this option will be set to VERTICAL.

sashpad
This option is used to represent the padding to be done
around each sash. The default value of this option is 0.

sashwidth
This option indicates the width of the sash. The default value
of this option is 2 pixels.

sashrelief
This option is used to represent the type of border around
each of the sash. The default value of this option is FLAT

showhandle
To display the handles, the value of this option should be set
to true. The default value of this option is false.

This option represents the width of the widget. If we do not


width specify the height then the height will be calculated by
the height of the child widgets.

relief
This option indicates the type of border. The default value
of this option is FLAT.
TKINTER PANEDWINDOW WIDGET METHODS:
Following are some methods used with PanedWindow widget:

Method
Description
Name

config(options)
This method is mainly used to configure any widget
with some specified options.

get(startindex,endindex)
This method is used to get the text at the specified
given range.

add(child,options)
This method is used to add a window to a parent
window.

TKINTER PANEDWINDOW WIDGET EXAMPLE


Below we have a basic example for the understanding of the PanedWindow
widget. Let us see the code snippet given below:
from tkinter import *

# event handler for button


def addition():
x = int(e1.get())
y = int(e2.get())
leftdata = str(x+y)
leftinput.insert(1, leftdata)
# first paned window
w1 = PanedWindow()
w1.pack(fill=BOTH, expand=1)

leftinput = Entry(w1, bd=5)


w1.add(leftinput)
# second paned window
w2 = PanedWindow(w1, orient=VERTICAL)
w1.add(w2)
e1 = Entry(w2)
e2 = Entry(w2)

w2.add(e1)
w2.add(e2)
bottomBtn = Button(w2, text="Addition", command=addition)
w2.add(bottomBtn)

mainloop()

As you can see above, in the output, we have an application window, in


which we have 3 tkinter Entry widgets and 1 tkinter button widget, stacked
using 2 PanedWindow widgets packed vertically besides each other.
If you will provide, two numbers in the right side entry widgets and then
click on the Addition button, the result of addition of the numbers in the
right, will be shown in the entry widget on the left hand side.

TKINTER PANEDWINDOW WIDGET - MULTIPLE PANES


EXAMPLE
Let us see another code snippet of this widget given below:
from tkinter import *
from tkinter import tk
win = Tk()

pw = PanedWindow(orient ='vertical')
#creating Button widget
top = tk.Button(pw, text ="Just Click Me!!!\nI am a Button")
top.pack(side=TOP)
#Adding button widget to the panedwindow
pw.add(top)
#Creating Checkbutton Widget
bot = Checkbutton(pw, text="I am Checkbutton Choose Me!")
bot.pack(side=TOP)
pw.add(bot)

label = Label(pw, text="I am a Label")


label.pack(side=TOP)
pw.add(label)

string = StringVar()

entry = Entry(pw, textvariable=string, font=('arial', 15, 'bold'))


entry.pack()

# This is used to force focus on particular widget


# that means widget is already selected for some operations
entry.focus_force()
pw.add(entry)
pw.pack(fill = BOTH, expand = True)

# To show sash
pw.configure(sashrelief = RAISED)
mainloop()

In the above code example, we have create multiple widgets inside a


panedwindow widget. We have also used StringVar() variable and we have
used the focus_force() function to have entry widget in focus when the
application is loaded.

Python Tkinter LabelFrame Widget


In this tutorial, we will cover the Tkinter LabelFrame widget in Python with
its syntax and few examples. The LabelFrame widget is mainly used to draw
borders around the child widgets.
This widget is a bordered container widget and is used to group the
related widgets in a Tkinter application to provide a better user
experience to the user.
For example, we can group the radiobutton widgets used in an
application using the labelframe widget.
One can also add a title for the LabelFrame widget(we will see this in
the code example).
The LabelFrame widget is simply a variant of the Frame widget and
it has all the features of a frame.
Note: If you have used HTML for web development, then the labelframe is
just like HTML fieldset tag.

TKINTER LABELFRAME WIDGET


The syntax of the LabelFrame widget is given below. Let us see:
w = LabelFrame(master, option=value)
In the above syntax, the master parameter denotes the parent window. You
can use many options to configure the labelframe and these options are written
as comma-separated key-value pairs.

TKINTER LABELFRAME WIDGET OPTIONS:


Following are the various options used with LabelFrame widgets:

Name of
Description
the Option
height This option is used to represent the height of the
widget.

width This option is used to represent the width of the frame.

text
This option represents the string containing the text of
the Label.

relief
This option represents the style of the border.The
default value of this option is GROOVE

padx
This option represents the horizontal padding of the
widget

pady
This option represents the vertical padding of the
widget

font
This option represents the font type of the text of the
widget

highlighthickness
This option represents the width of the focus highlight
border

This option indicates the color of the focus highlight


highlightbackground border at the time when the widget doesn't have the
focus

highlightcolor
This option indicates the color of the focus highlight
when the widget is under the focus
bg
This option indicates the background color of the
widget

This option is used to represent the size of the border


bd around the indicator.The default value of this option is
2 pixels.

Class The default value of this option is LabelFrame.

This option is mainly used to specify which colomap to


be used for this widget.With the help of this option, we
colormap can reuse the colormap of another window on this
widget.The colormap means 256 colors that are used to
form the graphics

The LabelFrame becomes the container widget if we


container will set the value of this option to true.The default value
of this option is false

This option will convert the mouse pointer to the


cursor specified cursor type and it can be set to an arrow, dot,
etc

fg
This option is used to indicate the foreground color of
the widget

This option represents the exact position of the text


labelAnchor inside the widget. The default value of this option
is NW(north-west)
This option indicates the widget to be used for the
labelwidget label. Also,the frame uses the text for the label if no
value specified

TKINTER LABELFRAME WIDGET EXAMPLE


Below we have a basic example of the LabelFrame widget. Let us see the
code snippet given below:
from tkinter import *

win = Tk()
win.geometry("300x200")
labelframe1 = LabelFrame(win, text="Happy Thoughts!!!")
labelframe1.pack(fill="both", expand="yes")

toplabel = Label(labelframe1, text="You can put your happy thoughts here")


toplabel.pack()
labelframe2 = LabelFrame(win, text = "Changes You want!!")
labelframe2.pack(fill="both", expand = "yes")

bottomlabel = Label(labelframe2, text = "You can put here the changes you want,If any!")
bottomlabel.pack()
win.mainloop()
As you can see in the output above, we have created two labelframe widgets,
in which we have added text for the labelframe widgets, and inside the
labelframe widget we have one label widget. We can have as many widgets
inside the labelframe widget, as we want.

Python Tkinter MessageBox


In this tutorial, we will cover how to create and use Tkinter
MessageBox while developing desktop applications.
In order to display message boxes in a desktop application, we use the
MessageBox module in Tkinter.
There are various functions present in this module which helps
to provide an appropriate type of message according to the
requirement.
With the help of this module, we can create pop-up message boxes to
take user input.
The functions of the MessageBox module are as
follows: showError() , askretrycancel() , showwarning() , etc., all of which are
used to create a messagebox.

TKINTER MESSAGEBOX
To use the messagebox module, we first need to import it in our python
script:
from tkinter import messagebox
Then following is the basic syntax to use the messagebox:
messagebox.function_name(title, message [, options])
In the above syntax, we have used the following:
function_name
This is used to indicate the name of the appropriate MessageBox
Function.
title
This is used to indicate the text to be displayed in the title bar of the
appropriate message box.
message
This is used to indicate the text to be displayed as a message in the
message box.
options
It is used to indicate various options in order to configure the
MessageBox. There are two values of it and these
are default and parent.
default: It is used to specify a default button such as ABORT,
RETRY, IGNORE.

parent: It is used to specify a window on the top of which we


will display the MessageBox.
The functions present in the MessageBox module uses the same syntax but
the functionalities of each function are different.
Let us see a few functions of the Tkinter MessageBox module.
TKINTER MESSAGEBOX - SHOWWARNING()

This method is used to display any warning to the user in a Python


application.
Here is a code for the same:
from tkinter import *

from tkinter import messagebox


win = Tk()
win.geometry("200x200")
messagebox.showwarning("warning","This is a Warning")

win.mainloop()

TKINTER MESSAGEBOX - ASKQUESTION()

This method in MessageBox is mainly used to ask some question to the


user which can be answered either in Yes or No.
The code for this method is as follows:
from tkinter import *
from tkinter import messagebox

win = Tk()
win.geometry("100x100")
messagebox.askquestion("Confirm","Are you sure about it?")
win.mainloop()
TKINTER MESSAGEBOX - ASKRETRYCANCEL()

If you want to ask a user to do any particular task or not then this method
will be used.
Let us see the code for the same:
from tkinter import *
from tkinter import messagebox
win= Tk()
win.geometry("100x100")
messagebox.askretrycancel("Application"," wanna try again?")

win.mainloop()
TKINTER MESSAGEBOX - SHOWERROR()

To display an error message this method will be used.


Let us see the code snippet given below:
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.showerror("errorWindow","oops!!!Error")
top.mainloop()
Using all the above-mentioned Widgets, we can create amazing GUI
applications.

SUMMARY:
So in this tutorial, we got a basic introduction to Trinket Widgets. In our
upcoming tutorial pages, we will cover each widget in detail with their
respective code examples.
Python Tkinter Geometry Manager
In this tutorial, we will learn how to control the layout of the
Application with the help of the Tkinter Geometry Managers.

CONTROLLING TKINTER APPLICATION LAYOUT


In order to organize or arrange or place all the widgets in the parent
window, Tkinter provides us the geometric configuration of the widgets.
The GUI Application Layout is mainly controlled by Geometric Managers of
Tkinter.
It is important to note here that each window and Frame in your application is
allowed to use only one geometry manager. Also, different frames can use
different geometry managers, even if they're already assigned to a frame or
window using another geometry manager.
There are mainly three methods in Geometry Managers:

Let us discuss each method in detail one by one.

1. TKINTER PACK() GEOMETRY MANAGER


The pack() method mainly uses a packing algorithm in order to place
widgets in a Frame or window in a specified order.
This method is mainly used to organize the widgets in a block.
PACKING ALGORITHM:
The steps of Packing algorithm are as follows:
Firstly this algorithm will compute a rectangular area known as
a Parcel which is tall (or wide) enough to hold the widget and then it
will fill the remaining width (or height) in the window with blank
space.
It will center the widget until any different location is specified.
This method is powerful but it is difficult to visualize.
Here is the syntax for using pack() function:
widget.pack(options)
The possible options as a parameter to this method are given below:
fill
The default value of this option is set to NONE. Also, we can set it
to X or Y in order to determine whether the widget contains any
extra space.
side
This option specifies which side to pack the widget against. If you
want to pack widgets vertically, use TOP which is the default
value. If you want to pack widgets horizontally, use LEFT.
expand
This option is used to specify whether the widgets should be
expanded to fill any extra space in the geometry master or not. Its
default value is false . If it is false then the widget is not
expanded otherwise widget expands to fill extra space.

TKINTER PACK() GEOMETRY MANAGER EXAMPLE:


Let us discuss an example where we will see what happens when
you pack() three colored Frame widgets(here is the Tkinter Frame Widget)
into a window:
import tkinter as tk
win = tk.Tk()
# add an orange frame
frame1 = tk.Frame(master=win, width=100, height=100, bg="orange")
frame1.pack()
# add blue frame
frame2 = tk.Frame(master=win, width=50, height=50, bg="blue")
frame2.pack()

# add green frame


frame3 = tk.Frame(master=win, width=25, height=25, bg="green")
frame3.pack()
window.mainloop()

According to the output of the above code, the pack() method just places
each Frame below the previous one by default, in the same order in which
they're assigned to the window.

TKINTER PACK() WITH PARAMETERS


Let's take a few more code examples using the parameters of this function
like fill , side and, expand .
You can set the fill argument in order to specify in which direction you want
the frames should fill. If you want to fill in the horizontal direction then the
option is tk.X , whereas, tk.Y is used to fill vertically, and to fill in both
directions tk.BOTH is used.
Let's take another example where we will stack the three frames so that each
one fills the whole window horizontally:
import tkinter as tk

win= tk.Tk()
frame1 = tk.Frame(master=win, height=80, bg="red")
# adding the fill argument with
# horizontal fill value
frame1.pack(fill=tk.X)

frame2 = tk.Frame(master=win, height=50, bg="yellow")


frame2.pack(fill=tk.X)
frame3 = tk.Frame(master=win, height=40, bg="blue")
frame3.pack(fill=tk.X)

win.mainloop()

In the above output, you can see that the frames fill the entire width of the
application window because we used the tk.X value for the fill parameter.
Now let's take another code example, where we will be using all options,
namely, fill , side , and expand options of the pack() method:
import tkinter as tk

win = tk.Tk()
frame1 = tk.Frame(master=win, width=200, height=100, bg="Yellow")
# setting fill, side and expand
frame1.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)

frame2 = tk.Frame(master=win, width=100, bg="blue")


frame2.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)
frame3 = tk.Frame(master=win, width=50, bg="green")
frame3.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)

win.mainloop()

If you will run this above code in your system then you can see this output is
able to expand in both directions.

2. TKINTER GRID() GEOMETRY MANAGER


The most used geometry manager is grid() because it provides all the power
of pack() function but in an easier and maintainable way.
The grid() geometry manager is mainly used to split either a window or frame
into rows and columns.
You can easily specify the location of a widget just by calling grid()
function and passing the row and column indices to the row and column
keyword arguments, respectively.
Index of both the row and column starts from 0 , so a row index of 2 and
a column index of 2 tells the grid() function to place a widget in
the third column of the third row(0 is first, 1 is second and 2 means
third).
Here is the syntax of the grid() function:
widget.grid(options)
The possible options as a parameter to this method are given below:
Column
This option specifies the column number in which the widget is to
be placed. The index of leftmost column is 0.
Row
This option specifies the row number in which the widget is to be
placed. The topmost row is represented by 0.
Columnspan

This option specifies the width of the widget. It mainly represents


the number of columns up to which, the column is expanded.
Rowspan
This option specifies the height of the widget. It mainly represents
the number of rows up to which, the row is expanded.
padx, pady
This option mainly represents the number of pixels of padding to be
added to the widget just outside the widget's border.
ipadx, ipady
This option is mainly used to represents the number of pixels of
padding to be added to the widget inside the widget's border.
Sticky
If any cell is larger than a widget, then sticky is mainly used to
specify the position of the widget inside the cell. It is basically
concatenation of the sticky letters which represents the position of
the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.

TKINTER GRID() GEOMETRY MANAGER EXAMPLE:


The following code script will help you to create a 5 × 3 grid of frames
with Label widgets packed into them:
import tkinter as tk
win = tk.Tk()

for i in range(5):
for j in range(3):
frame = tk.Frame(
master = win,
relief = tk.RAISED,
borderwidth = 1
)
frame.grid(row=i, column=j)
label = tk.Label(master=frame, text=f"Row {i}\nColumn {j}")
label.pack()

win.mainloop()

If you want to add some padding then you can do it by using the following
code snippet:
import tkinter as tk
win = tk.Tk()
for i in range(5):
for j in range(3):
frame = tk.Frame(
master=win,
relief=tk.RAISED,
borderwidth=1
)
frame.grid(row=i, column=j, padx=5, pady=5)
label = tk.Label(master=frame, text=f"Row {i}\nColumn {j}")
label.pack()
win.mainloop()

As you can see in the code example above, we have used


the padx and pady parameters because of which padding is applied outside
the widget. To add padding inside the Frame widget, use the
parameters ipadx and ipady in your code.
Similarly, do try using other parameters too for the grid() geometry manager.

3. TRINKET PLACE() GEOMETRY MANAGER


The place() Geometry Manager organizes the widgets to place them in a
specific position as directed by the programmer.
This method basically organizes the widget in accordance with its x
and y coordinates. Both x and y coordinates are in pixels.
Thus the origin (where x and y are both 0 ) is the top-left corner of the
Frame or the window.

Thus, the y argument specifies the number of pixels of space from the
top of the window, to place the widget, and the x argument specifies
the number of pixels from the left of the window.
Here is the syntax of the place() method:
widget.place(options)
The possible options as a parameter to this method are given below:
x, y
This option indicates the horizontal and vertical offset in the
pixels.
height, width
This option indicates the height and weight of the widget in the
pixels.
Anchor
This option mainly represents the exact position of the widget
within the container. The default value (direction) is NW that is (the
upper left corner).
bordermode
This option indicates the default value of the border type which
is INSIDE and it also refers to ignore the parent's inside the border.
The other option is OUTSIDE .
relx, rely
This option is used to represent the float between 0.0 and 1.0 and it
is the offset in the horizontal and vertical direction.
relheight, relwidth
This option is used to represent the float value between 0.0 and 1.0
indicating the fraction of the parent's height and width.

TKINTER PLACE() GEOMETRY MANAGER EXAMPLE:


The code snippet for this is given below:
from tkinter import *
top = Tk()
top.geometry("400x250")
Username = Label(top, text = "Username").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()

In the above code example, we have used Tkinter Label and Tkinter Entry
widget, we will cover them in detail in the upcoming tutorials.

SUMMARY:
In this tutorial, we learned how we can position our widgets inside the frame
or window of our GUI application. We learned about the three Tkinter
geometry managers, namely, pack(), grid() and place().
From the next tutorial, we will start covering different Tkinter widgets.
Calculator Application using
Tkinter
In this tutorial, we will cover how to create a simple calculator app using
Python Tkinter.
As in our previous tutorials, we have covered how to create tkinter
buttons, tkinter labels, tkinter entry, tkinter frames and tkinter checkbuttons,
and many more. Now with the help of all the widgets discussed in previous
sections, we are going to create a Calculator App using Tkinter.
Here is how our calculator will look, which is made by using the input
field, buttons and for the calculation purpose we will use logic in our code
defined in functions, like if you want to add two numbers then behind this
there must be a logic for addition purpose, similarly for substraction,
multiplication, etc, we have created functions whose task is to perform these
operations.
We have an Input Field in which the user input will be shown and the final
result of the calculation will be displayed.
And the buttons are like 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, -, *, /, =, ., and C(clear
button)

WHAT IS A CALCULATOR?
For those who do not know, a calculator is basically a program on
a computer that simulates the behavior of any hand-held calculator useful
for performing Mathematical Calculations. It is a very basic device used in
our every day lives. Now all the smartphones also have a Calculator
application in them.
While creating any GUI Application there are mainly two steps:
The first step is to create a User Interface

The second step is the most important one and in this, to add
functionalities to the GUI
Now let's begin with creating a simple calculator app using Tkinter in
Python which is used for basic arithmetic calculations.

CALCULATOR APP CODE


Now it's time to take a look at the code to create a Calculator App using
Tkinter:
from tkinter import *

win = Tk() # This is to create a basic window


win.geometry("312x324") # this is for the size of the window
win.resizable(0, 0) # this is to prevent from resizing the window
win.title("Calculator")

###################Starting with functions ####################


# 'btn_click' function :
# This Function continuously updates the
# input field whenever you enters a number
def btn_click(item):
global expression
expression = expression + str(item)
input_text.set(expression)

# 'bt_clear' function :This is used to clear


# the input field
def bt_clear():
global expression
expression = ""
input_text.set("")

# 'bt_equal':This method calculates the expression


# present in input field
def bt_equal():
global expression
result = str(eval(expression)) # 'eval':This function is used to evaluates the string expression directly
input_text.set(result)
expression = ""

expression = ""
# 'StringVar()' :It is used to get the instance of input field

input_text = StringVar()
# Let us creating a frame for the input field

input_frame = Frame(win, width=312, height=50, bd=0, highlightbackground="black",


highlightcolor="black", highlightthickness=2)
input_frame.pack(side=TOP)

#Let us create a input field inside the 'Frame'


input_field = Entry(input_frame, font=('arial', 18, 'bold'), textvariable=input_text, width=50,
bg="#eee", bd=0, justify=RIGHT)

input_field.grid(row=0, column=0)
input_field.pack(ipady=10) # 'ipady' is internal padding to increase the height of input field

#Let us creating another 'Frame' for the button below the 'input_frame'
btns_frame = Frame(win, width=312, height=272.5, bg="grey")

btns_frame.pack()
# first row

clear = Button(btns_frame, text = "C", fg = "black", width = 32, height = 3, bd = 0, bg = "#eee", cursor
= "hand2", command = lambda: bt_clear()).grid(row = 0, column = 0, columnspan = 3, padx = 1, pady
= 1)
divide = Button(btns_frame, text = "/", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor
= "hand2", command = lambda: btn_click("/")).grid(row = 0, column = 3, padx = 1, pady = 1)

# second row
seven = Button(btns_frame, text = "7", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor
= "hand2", command = lambda: btn_click(7)).grid(row = 1, column = 0, padx = 1, pady = 1)
eight = Button(btns_frame, text = "8", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(8)).grid(row = 1, column = 1, padx = 1, pady = 1)

nine = Button(btns_frame, text = "9", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(9)).grid(row = 1, column = 2, padx = 1, pady = 1)
multiply = Button(btns_frame, text = "*", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee",
cursor = "hand2", command = lambda: btn_click("*")).grid(row = 1, column = 3, padx = 1, pady = 1)

# third row
four = Button(btns_frame, text = "4", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1)

five = Button(btns_frame, text = "5", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(5)).grid(row = 2, column = 1, padx = 1, pady = 1)
six = Button(btns_frame, text = "6", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(6)).grid(row = 2, column = 2, padx = 1, pady = 1)

minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor
= "hand2", command = lambda: btn_click("-")).grid(row = 2, column = 3, padx = 1, pady = 1)
# fourth row

one = Button(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1, pady = 1)
two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady = 1)

three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(3)).grid(row = 3, column = 2, padx = 1, pady = 1)

plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor =
"hand2", command = lambda: btn_click("+")).grid(row = 3, column = 3, padx = 1, pady = 1)

# fourth row
zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(0)).grid(row = 4, column = 0, columnspan = 2, padx = 1, pady
= 1)

point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor
= "hand2", command = lambda: btn_click(".")).grid(row = 4, column = 2, padx = 1, pady = 1)
equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee",
cursor = "hand2", command = lambda: bt_equal()).grid(row = 4, column = 3, padx = 1, pady = 1)

win.mainloop()
There are a variety of functions in Tkinter with the help of them it becomes
easy and convenient to make a simple calculator just with this little code.
Now we will show you a snapshot as the output of the above code. And yes
you can implement it on your system for more clear understanding of
Calculator App Using Tkinter:

SUMMARY:
In this tutorial, we developed a basic Calculator application using Tkinter and
various widgets of Tkinter about which we have covered in our Tkinter
Tutorial. Click on Next to see more Apps developed using Tkinter as this will
help you practice what you have learned.
Text Editor Application Using
Tkinter
In this tutorial, we will help you to build a simple Text Editor Application
using Tkinter which is a very good beginner project for Tkinter.
Text Editor Application is an application where you can write your text, open
any text file, you can edit any text file and you can also save a file if you
want. In this tutorial, we will build a Text Editor Application from scratch.
Essential Elements for the Text editor application are as follows:
There is a Button widget called btn_open that is used for opening a file
for editing
Second one is a Button widget called btn_save for saving a file
Third, there is a Text widget called txt_edit for creating and editing any
text file.
The arrangement of three widgets is done in a way such that the two buttons
are on the left-hand side of the window, and the text box is on the right-hand
side. The minimum height of the whole window should be 900 pixels
and txt_edit should have a minimum width of 900 pixels. And The whole
layout should be responsive if the window is resized, then txt_edit is resized
as well. The width of the Frame that holds the buttons should not change.
Let us show you with a rough sketch of how this text editor will look like:
The desired layout of the Text Editor Application can be achieved using
the .grid() geometry manager. And this layout contains a single row and two
columns:
On the left side, there is A narrow column for the buttons
On the right side, there is A wider column for the text box
In order to set the minimum sizes for the window and txt_edit , you just need
to set the minsize parameters of the window
methods .rowconfigure() and .columnconfigure() to 900. In order to handle the
resizing, the weight parameters of these methods will be set to 1.
If you want both the buttons in the same column then you’ll need to create
a Frame widget called fr_buttons . According to the above-shown sketch, the
two buttons should be stacked vertically inside of this frame,
having btn_open on top. This can be done either by .grid() or .pack() geometry
manager. For now, you’ll just need to stick with .grid() as it is easier to work
with it.
Let us start with the code for building the Application:

1. CREATING ALL THE NEEDED WIDGETS


The code snippet that is used is as follows:
import tkinter as tk
window = tk.Tk()
window.title("Text Editor Application")
window.rowconfigure(0, minsize=900, weight=1)
window.columnconfigure(1, minsize=900, weight=1)

txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window)
btn_open = tk.Button(fr_buttons, text="Open")
btn_save = tk.Button(fr_buttons, text="Save As...")

EXPLANATION OF THE ABOVE CODE:


The first command is used to import the tkinter .
Then the next two lines are used to create a new window with the
title "Text Editor Application" .
The next two lines of code are used to set the row and column
configurations.
Then the lines from 9 to 12 will create the four widgets you’ll need for
the text box, the frame, and the open and save buttons.
window.rowconfigure(0, minsize=900, weight=1)
The above-given line in the code indicates The minsize parameter
of .rowconfigure() is set to 900 and weight is set to 1. The first argument is 0 ,
which is used to set the height of the first row to 900 pixels and makes sure
that the height of the row grows proportionally to the height of the window.
There’s only one row in the application layout, so these settings are applied
to the entire window.
Then take a look at this line in the code :
window.columnconfigure(1, minsize=900, weight=1)
In the above code the .columnconfigure() to set the width and weight attributes of
the column with index 1 to 900 and 1 , respectively. Keep it in mind that,
row and column indices are zero-based, so these settings apply only to the
second column. By configuring the second column, the text box will expand
and contract naturally when the window is resized, while the column
containing the buttons will always remain at a fixed width.

2.CREATION OF APPLICATION LAYOUT


btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
btn_save.grid(row=1, column=0, sticky="ew", padx=5)
The above two lines of code will create a grid with two rows and one
column in the fr_buttons frame since both btn_open and btn_save have their
master attribute set to fr_buttons . btn_open is put in the first row and btn_save will
be in the second row so that btn_open appears above btn_save in the layout, as
planned in the above sketch.

The btn_open and btn_save both have their sticky attributes set to "ew" ,
which forces the buttons to expand horizontally in both directions and
in order to fill the entire frame. It makes sure both buttons are of the
same size.
You place 5 pixels of padding around each button just by setting
the padx and pady parameters to 5. The btn_open has vertical padding.
Because it’s on top, the vertical padding offsets the button down from
the top of the window a bit and makes sure that there’s a small gap
between this and btn_save .
Now the fr_buttons is laid out and ready to go, you can just set up the grid
layout for the rest of the window now:
fr_buttons.grid(row=0, column=0, sticky="ns")
txt_edit.grid(row=0, column=1, sticky="nsew")
These above two lines of code are used to create a grid with one row and
two columns for window . You place fr_buttons in the first column
and txt_edit in the second column so that fr_buttons appears to the left
of txt_edit in the window layout.
The sticky parameter for fr_buttons will be set to "ns" , which forces the whole
frame to expand vertically and fill the entire height of its column. txt_edit is
used to fill its entire grid cell because you set its sticky parameter to "nsew" ,
which forces it to expand in every direction.
Now we have just created the buttons but these do not work until we add
functioning to them So let's start adding the Functioning of Buttons:

1. FUNCTION TO OPEN THE FILE


The code snippet for open_file is as follows:
def open_file():
"""Open a file for editing."""
filepath = askopenfilename(
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if not filepath:
return
txt_edit.delete(1.0, tk.END)
with open(filepath, "r") as input_file:
text = input_file.read()
txt_edit.insert(tk.END, text)
window.title(f"Text Editor Application - {filepath}")

EXPLANATION:
The Lines from 3 to 5 use the askopenfilename dialog from
the tkinter.filedialog module to display a file open dialog and store the
selected file path to filepath .
Lines 6 and 7 checks to see if the user closes the dialog box or clicks
the Cancel button. If so, then filepath will be None , and the function
will return without executing any of the code to read the file and set the
text of txt_edit .
Line 8 clears the current contents of txt_edit using .delete() .
Lines 9 and 10 are used to open the selected file and .read() its contents
before storing the text as a string.
Line number 11 assigns the string text to txt_edit using .insert() .
Line 12 sets the title of the window so that it contains the path of the
open file.

2. FUNCTION TO SAVE THE FILE


The code snippet for save_file is as follows:
def save_file():
"""Save the current file as a new file."""
filepath = asksaveasfilename(
defaultextension="txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
)
if not filepath:
return
with open(filepath, "w") as output_file:
text = txt_edit.get(1.0, tk.END)
output_file.write(text)
window.title(f"Text Editor Application - {filepath}")
EXPLANATION:
Lines 3 to 6 use the asksaveasfilename dialog box to get the desired save
location from the user. The selected file path is stored in
the filepath variable.
Lines 7 and 8 checks to see if the user closes the dialog box or clicks
the Cancel button. If so, then filepath will be None , and the function will
return without executing any of the code to save the text to a file.
Line 9 creates a new file at the selected file path.
Line 10 extracts the text from txt_edit with .get() method and assigns it to
the variable text .
Line 11 writes text to the output file.
Line 12 updates the title of the window so that the new file path is
displayed in the window title.
Complete Source code is:
import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
def open_file():
"""Open a file for editing."""
filepath = askopenfilename(
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if not filepath:
return
txt_edit.delete(1.0, tk.END)
with open(filepath, "r") as input_file:
text = input_file.read()
txt_edit.insert(tk.END, text)
window.title(f"Text Editor Application - {filepath}")

def save_file():
"""Save the current file as a new file."""
filepath = asksaveasfilename(
defaultextension="txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
)
if not filepath:
return
with open(filepath, "w") as output_file:
text = txt_edit.get(1.0, tk.END)
output_file.write(text)
window.title(f"Text Editor Application - {filepath}")
window = tk.Tk()
window.title("Text Editor Application")
window.rowconfigure(0, minsize=800, weight=1)
window.columnconfigure(1, minsize=800, weight=1)

txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)
btn_open = tk.Button(fr_buttons, text="Open", command=open_file)
btn_save = tk.Button(fr_buttons, text="Save As...", command=save_file)

btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)


btn_save.grid(row=1, column=0, sticky="ew", padx=5)
fr_buttons.grid(row=0, column=0, sticky="ns")
txt_edit.grid(row=0, column=1, sticky="nsew")

window.mainloop()

As you can see in the output, we have a basic text editor application in
which we can write something and then save the text in a new file or use
the Open button to open a file in the editor and then edit it.
Music Player Application using
Tkinter
In this tutorial, we will create a Music Player Application in Python
using Tkinter and Pygame module.
In our daily life, we see every person has a hobby and that is listening to
music. So in order to listen to music, they all need a Music player(hardware
or software) where they can play their favorite songs. And we have to install
this music player on our computer, based the Operating system i.e Windows,
Macintosh, Android, Linux, etc. Then we can listen to our favorite songs.
Now we will help you to code and create a Music Player from scratch.

LIBRARIES USED FOR MUSIC PLAYER APPLICATION:


Now we will tell you about the Libraries we will use in our code :

1. TKINTER
We had already told you in the title of this page that we are going to use the
Tkinter library, which is a standard library for GUI creation. The Tkinter
library is most popular and very easy to use and it comes with many widgets
(these widgets helps in the creation of nice-looking GUI Applications).
Also, Tkinter is a very light-weight module and it is helpful in creating cross-
platform applications(so the same code can easily work
on Windows, macOS, and Linux)

To use all the functions of Tkinter you need to import it in your code and the
command for the same is:
from tkinter import *

2. PYGAME MODULE
Pygame is a Python module that works with computer graphics and sound
libraries and designed with the power of playing with different multimedia
formats like audio, video, etc. While creating our Music Player application,
we will be using Pygame's mixer.music module for providing different
functionality to our music player application that is usually related to the
manipulation of the song tracks.
Command used to install pygame is:
pip install pygame

To use this module into your code you need to write this:
import pygame

3. OS MODULE
There is no need to install this module explicitly, as it comes with the
standard library of Python. This module provides different functions for
interaction with the Operating System. In this tutorial, we are going to use the
OS module for fetching the playlist of songs from the specified
directory and make it available to the music player application.
To use this module in your code you need to import its and command for the
same is as follows:
import OS

After importing Libraries and modules, now it's time to create a basic
window where we will add our UI elements or Tkinter widgets. You can add
this code either after importing libraries or also at the end just before the
looping of the root window and the code is as follows:
root = Tk() # In order to create an empty window
# Passing Root to MusicPlayer Class
MusicPlayer(root)

MUSICPLAYER CLASS
Here we have the constructor and the other functions defined in the
MusicPlayer class.

1. _INIT_ CONSTRUCTOR
With the help of this constructor, we will set the title for the
window and geometry for the window. We will initiate pygame and
pygame mixer and then declare track variable and status variable.
We will then Create the Track Frames for Song label & status
label and then after Insert the Song Track Label and Status Label.
After that, we will create the Button Frame and insert play, pause,
unpause, and stop buttons into it.
Then we will create the playlist frame and add the scrollbar to it and
we will add songs into playlist.
The code snippet is as follows:
def __init__(self,root):
self.root = root
# Title of the window
self.root.title("MusicPlayer")
# Window Geometry
self.root.geometry("1000x200+200+200")
# Initiating Pygame
pygame.init()
# Initiating Pygame Mixer
pygame.mixer.init()
# Declaring track Variable
self.track = StringVar()
# Declaring Status Variable
self.status = StringVar()
# Creating the Track Frames for Song label & status label
trackframe = LabelFrame(self.root,text="Song Track",font=("times new
roman",15,"bold"),bg="Navyblue",fg="white",bd=5,relief=GROOVE)
trackframe.place(x=0,y=0,width=600,height=100)
# Inserting Song Track Label
songtrack = Label(trackframe,textvariable=self.track,width=20,font=("times new
roman",24,"bold"),bg="Orange",fg="gold").grid(row=0,column=0,padx=10,pady=5)
# Inserting Status Label
trackstatus = Label(trackframe,textvariable=self.status,font=("times new
roman",24,"bold"),bg="orange",fg="gold").grid(row=0,column=1,padx=10,pady=5)

# Creating Button Frame


buttonframe = LabelFrame(self.root,text="Control Panel",font=("times new
roman",15,"bold"),bg="grey",fg="white",bd=5,relief=GROOVE)
buttonframe.place(x=0,y=100,width=600,height=100)
# Inserting Play Button
playbtn =
Button(buttonframe,text="PLAYSONG",command=self.playsong,width=10,height=1,font=("times new
roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=0,padx=10,pady=5)
# Inserting Pause Button
playbtn = Button(buttonframe,text="PAUSE",command=self.pausesong,width=8,height=1,font=
("times new roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=1,padx=10,pady=5)
# Inserting Unpause Button
playbtn =
Button(buttonframe,text="UNPAUSE",command=self.unpausesong,width=10,height=1,font=("times
new roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=2,padx=10,pady=5)
# Inserting Stop Button
playbtn =
Button(buttonframe,text="STOPSONG",command=self.stopsong,width=10,height=1,font=("times new
roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=3,padx=10,pady=5)
# Creating Playlist Frame
songsframe = LabelFrame(self.root,text="Song Playlist",font=("times new
roman",15,"bold"),bg="grey",fg="white",bd=5,relief=GROOVE)
songsframe.place(x=600,y=0,width=400,height=200)
# Inserting scrollbar
scrol_y = Scrollbar(songsframe,orient=VERTICAL)
# Inserting Playlist listbox
self.playlist =
Listbox(songsframe,yscrollcommand=scrol_y.set,selectbackground="gold",selectmode=SINGLE,font=
("times new roman",12,"bold"),bg="silver",fg="navyblue",bd=5,relief=GROOVE)
# Applying Scrollbar to listbox
scrol_y.pack(side=RIGHT,fill=Y)
scrol_y.config(command=self.playlist.yview)
self.playlist.pack(fill=BOTH)
# Changing Directory for fetching Songs
os.chdir("PATH/OF/DIRECTORY")
# Fetching Songs
songtracks = os.listdir()
# Inserting Songs into Playlist
for track in songtracks:
self.playlist.insert(END,track)
In the code above, change the PATH/OF/DIRECTORY with appropriate
path where the song files are stored.

2. THE PLAYSONG() FUNCTION


Now we will define the Play Song Function and the code is:
def playsong(self):
# Displaying Selected Song title
self.track.set(self.playlist.get(ACTIVE))
# Displaying Status
self.status.set("-Playing")
# Loading Selected Song
pygame.mixer.music.load(self.playlist.get(ACTIVE))
# Playing Selected Song
pygame.mixer.music.play()

3. THE STOPSONG() FUNCTION


The code snippet to stop the song:
def stopsong(self):
# Displaying Status
self.status.set("-Stopped")
# Stopped Song
pygame.mixer.music.stop()

4. THE PAUSESONG() FUNCTION


The code snippet to pause the song:
def pausesong(self):
# Displaying Status
self.status.set("-Paused")
# Paused Song
pygame.mixer.music.pause()

5. THE UNPAUSESONG() FUNCTION


The code snippet to unpause the song:
def unpausesong(self):
# It will Display the Status
self.status.set("-Playing")
# Playing back Song
pygame.mixer.music.unpause()

6. ROOT WINDOW LOOPING


The command will be:
root.mainloop()
Now here are some of the screenshots of our application:
The Folder named studytonight where the code file and folder for songs is
placed looks like:

We will provide the path of the songs folder in our code where all songs are
placed in order to access them.
Now the following screenshot is to show you how the application will look
like:

WHENEVER YOU MADE A CLICK ON THE SONG IT WILL LOOK LIKE:

ON CLICKING THE PLAYSONG BUTTON:

ON CLICKING THE PAUSE BUTTON:

ON CLICKING THE STOP BUTTON:


So this was all about building the Music Player Application using Tkinter.
Hope you all like this application. Do share more ideas with us for Tkinter
based desktop application and we will definitely add more Tkinter projects to
our Tkinter tutorial.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy