Keith Tab W Tkinter Tutorial Learn Tkinter
Keith Tab W Tkinter Tutorial Learn Tkinter
Keith Tab W Tkinter Tutorial Learn Tkinter
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).
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.
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.
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.
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 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.
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.
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")
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:
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.
fg
This option represents the foreground
color of the button.
font
This option indicates the font of the
button.
image
This option indicates the image
displayed on the button.
underline
This option is used to underline the
text of the button.
win.geometry("200x100")
b = Button(win, text = "Submit")
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.
bg
This option is used to set
the background color.
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
cv.pack()
top.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.
fg
This option represents the text color
of the checkbutton.
font
This option indicates the font of the
checkbutton.
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.
selectimage
This option indicates the image on
the checkbutton when it is set.
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.
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
selectforeground
It is used to set the font of the
selected task.
win = Tk()
win.geometry("400x250")
name = Label(win, text = "Name").place(x = 30,y = 50)
height
This option is used to indicate
the height of the frame.
width
This option is used to indicate
the width of the frame.
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.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
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.
bg
This option is used for the
background color of 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.
width
This option indicates the width of the
widget.
win.geometry("400x250")
#creating a label
username = Label(win, text = "Username").place(x = 30,y = 50)
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.
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.
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.
Method Description
This method is mainly used to
activate(index) select the lines at the specified
index.
xview()
This method is used to make the
widget horizontally scrollable.
yview()
This method allows the Listbox
to be vertically scrollable.
bd
This option is used to indicate
the border width of the widget
image
This option is used to display an
image on the menu
add_radiobutton()
This method is used to add
the radiobutton to the menu.
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.
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.
fg
This option represents
the foreground color of the widget.
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.
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.
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.
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
pady
This option is used for the vertical
padding of the widget.
bg
This option represents the
background color of the widget.
borderwidth
This option is used to represent
the size of the border.
height
This option indicates the vertical
dimension of the widget
pady
This option represents the
vertical padding of the widget
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
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"))
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.
troughcolor
This option is used to set the
color for the trough
set(value) :
win = Tk()
win.geometry("200x100")
v = DoubleVar()
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.
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")
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.
width
This option represents the
width of the scrollbar.
troughcolor
This option is used to set the
color for the trough
repeatinterval
The default value of this option
is 100
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.
bd
This option represents the
border width of the widget.
font
This option is used to indicate
the font type of the text.
fg
This option indicates the text
color of the widget
Method Description
index(index)
This method is used to
get the specified index.
To remove the tag from the specified range this method is used
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", )
l.pack()
T.pack()
b1.pack()
b2.pack()
bd
To represent the border size of the
window
bg
To represent the background color
of the window
width
This option is used to represent the
width of the window
height
This option is used to represent the
height of the window
relief
This option indicates the type of the
window.
Method Description
title(string)
This method is used to define
the title for the window.
positionfrom(who)
This method is used to define
the position controller
sizefrom(who)
This method is used to define
the size controller.
deiconify()
This method is mainly used
to display the window.
To indicate a system-
frame() dependent window
identifier this method is used.
win.geometry("200x200")
def open():
top = Toplevel(win)
top.mainloop()
win.mainloop()
In the code above, we have created a Toplevel widget that is created and
started when the Button is clicked.
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
font
This option specifies the font
type of text inside the widget.
from_
This option is used to indicate
the starting range of the widget
width
This option indicates the width
of the widget.
vcmd
This option is similar to
validatecommand.
bg
This option represents the background color of the
widget.
sashwidth
This option indicates the width of the sash. The
default value of this option is 2 pixels.
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:
e1 = Entry(w2)
e2 = Entry(w2)
w2.add(e1)
w2.add(e2)
bottomBtn = Button(w2, text="Addition", command=addition)
w2.add(bottomBtn)
mainloop()
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)
string = StringVar()
entry = Entry(pw, textvariable=string, font=('arial', 15, 'bold'))
entry.pack()
# To show sash
pw.configure(sashrelief = RAISED)
mainloop()
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.
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
bg
This option indicates the
background color of the widget
Class
The default value of this option
is LabelFrame.
win = Tk()
win.geometry("300x200")
labelframe1 = LabelFrame(win, text="Happy Thoughts!!!")
labelframe1.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.
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.
win.mainloop()
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()
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.
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.
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.
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 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.
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.
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.
bd
This option is used to indicate the border width 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
relief
This option is used to specify the border type. Its default
value is RAISED.
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.
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.
add(type, options)
This method is used to add the
specific menu item to the menu.
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.
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:
This option
mainly represents the
activeforeground font color of the widget
at the time when the
widget is under the focus
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.
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.
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.
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
pady
This option is used for the vertical
padding of the widget.
bg
This option represents the
background color of the widget.
borderwidth
This option is used to represent
the size of the border.
pady
This option represents the
vertical padding of the widget
text
This option indicates the text to
be displayed on the radiobutton.
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
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.
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"))
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.
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
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
state
By default, the state of the scale widget is active. To
make it unresponsive you can also set it to DISABLED
variable
This option is used to represent the control variable
for the scale
troughcolor This option is used to set the color for the trough
set(value) :
v = DoubleVar()
scale = Scale( win, variable=v, from_=1, to=50, orient=HORIZONTAL)
scale.pack(anchor=CENTER)
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.
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)
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.
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.
command
This option will be set to the procedure associated
which is called every time the scrollbar is moved.
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
orient
This option can be set to either horizontal or vertical
depending upon the orientation of the scrollbar.
troughcolor This option is used to set the color for the trough
win= Tk()
sbb = Scrollbar(win)
sbb.pack(side = RIGHT, fill = Y)
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.
Name of
Description
the option
bg
This option indicates the background color of the
widget.
font This option is used to indicate the font type of the text.
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.
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.
spacing1
This option indicates the vertical space to insert above
each line of the text.
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.
Method Description
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
To remove the tag from the specified range this method is used
# 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"""
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.
Name
of
Description
the
option
cursor
This option will convert the mouse pointer to the specified
cursor type and it can be set to an arrow, dot, etc.
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.
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
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.
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
win.geometry("200x200")
def open():
top = Toplevel(win)
top.mainloop()
Name of
the Description
Option
bg
This option is used for the background color of the
widget.
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
relief
This option indicates the type of border. The default
value of this option is SUNKEN.
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.
wrap
This option is mainly used to wrap-up the up and down
button of the Spinbox
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
win = Tk()
win.geometry("300x200")
w = Label(win, text ='StudyTonight', fg="navyblue",font = "50")
w.pack()
Name
of
Description
the
Option
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.
handlesize
This option represents the size of the handle and its default
value is 8 pixels. Also, the handle will always be in square
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.
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.
w2.add(e1)
w2.add(e2)
bottomBtn = Button(w2, text="Addition", command=addition)
w2.add(bottomBtn)
mainloop()
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)
string = StringVar()
# To show sash
pw.configure(sashrelief = RAISED)
mainloop()
Name of
Description
the Option
height This option is used to represent the height of the
widget.
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
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
fg
This option is used to indicate the foreground color of
the widget
win = Tk()
win.geometry("300x200")
labelframe1 = LabelFrame(win, text="Happy Thoughts!!!")
labelframe1.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.
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.
win.mainloop()
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()
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.
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.
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)
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)
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.
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()
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.
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.
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_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:
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...")
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:
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.
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)
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.
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)
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: