Projects With Python (GUI & Tkinter)
Projects With Python (GUI & Tkinter)
Table of Contents
Contents
About the Authors
Table of Contents
Tkinter GUI Projects with Python
PART 1: Introduction to Python Tkinter Module
Prerequisites for Tkinter
GUI Programming in Python
What is Tkinter?
What are Tcl, Tk, and Tkinter?
Install Tkinter
Adding Tk to your Applications
First Tkinter Example
Tkinter Methods used above:
Summary:
PART 2: Tkinter Windows, Widgets and Frames
Introduction to Tkinter Windows and Widgets
Tkinter Event-Driven Processing
Tkinter Windows
Tkinter Top-Level Window
Tkinter Widgets
Tkinter Frames
Tkinter Basic Example
Summary:
PART 3: Tkinter Windows
Tkinter Windows
Tkinter Windows Example:
Tkinter Customized Window
Summary:
PART 4: Python Tkinter Widgets
Tkinter Widgets
Summary:
PART 5: Python Tkinter Geometry Manager
Controlling Tkinter Application Layout
1. Tkinter pack() Geometry Manager
Packing Algorithm:
Tkinter pack() Geometry Manager Example:
Tkinter pack() with Parameters
2. Tkinter grid() Geometry Manager
Tkinter grid() Geometry Manager Example:
3. Trinket place() Geometry Manager
Tkinter place() Geometry Manager Example:
Summary:
PART 6: Python Tkinter Label Widget
Tkinter Label Widget
Tkinter Label Widget Example
Tkinter Label Widget - Another Example
Summary:
PART 7: Python Tkinter Button Widget
Tkinter Button Widget
Tkinter Button Widget Example
Tkinter Button Widget - Add style and Event handler
Summary:
PART 8: Python Tkinter Checkbutton Widget
Tkinter Checkbutton Widget
Tkinter Checkbutton Widget Methods:
Tkinter Checkbutton Widget Example
Summary
PART 9: Python Tkinter Radiobutton Widget
Tkinter Radiobutton Widget
Tkinter Radiobutton Widget Methods:
Tkinter Radiobutton Widget Example
Tkinter Radiobutton Widget Another Example
Summary:
PART 10: Python Tkinter Entry Widget
Tkinter Entry Widget
Tkinter Entry Widget Example
Summary
PART 11: Python Tkinter Message Widget
Tkinter Message Widget
Tkinter Message Widget Example
Summary:
PART 12: Python Tkinter Menu Widget
Tkinter Menu Widget
Tkinter Menu Widget Example
Summary:
PART 13: Python Tkinter Menubutton Widget
Tkinter Menubutton Widget
Tkinter Menubutton Widget Options:
Tkinter Menubutton Widget Example
PART 14: Python Tkinter Frame Widget
Tkinter Frame Widget
Tkinter Frame Widget Example
Summary
PART 15: Python Tkinter Canvas Widget
Tkinter Canvas Widget
Tkinter Canvas Widget Basic Example
Tkinter Canvas Widget - Pie Chart using Arcs
Summary:
PART 16: Python Tkinter Listbox Widget
Tkinter Listbox Widget
Tkinter Listbox Widget Options:
Tkinter ListBox Widget Example
Summary:
PART 17: Python Tkinter Scrollbar Widget
Tkinter Scrollbar Widget
Tkinter Scrollbar Widget Options:
Tkinter Scrollbar Widget Methods:
Tkinter Scrollbar Widget Example
Summary:
PART 18: Python Tkinter Scale Widget
Tkinter Scale Widget
Tkinter Scale Widget Methods
Tkinter Scale Widget - Horizontal Example
Tkinter Scale Widget - Vertical Example
Summary:
PART 19: Python Tkinter Toplevel Widget
Python Tkinter Toplevel Widget
Tkinter Toplevel Widget Example
Summary:
PART 20: Python Tkinter Spinbox Widget
Tkinter Spinbox Widget
Tkinter Spinbox Widget Example
Summary:
PART 21: Python Tkinter LabelFrame Widget
Tkinter LabelFrame Widget
Tkinter LabelFrame Widget Example
Summary:
PART 22: Python Tkinter PanedWindow Widget
Tkinter PanedWindow Widget
Tkinter PanedWindow Widget Methods:
Tkinter PanedWindow Widget Example
Tkinter PanedWindow Widget - Multiple Panes Example
Summary:
PART 23: Python Tkinter Text Widget
Tkinter Text Widget
Tkinter Text Widget Methods:
Methods for Tag Handling
Methods for Mark Handling
Tkinter Text Widget Example
Summary:
PART 24: Python Tkinter MessageBox
Tkinter MessageBox
Tkinter MessageBox - showwarning()
Tkinter MessageBox - askquestion()
Tkinter MessageBox - askretrycancel()
Tkinter MessageBox - showerror()
Summary:
PART 25: Calculator Application using Tkinter (Python Project)
What is a Calculator?
Calculator App Code
Summary:
PART 26: Text Editor Application Using Tkinter (Python Project)
1. Creating all the needed widgets
Explanation of the above code:
2.Creation of Application Layout
1. Function to Open the File
Explanation:
2. Function to Save the File
Explanation:
PART 27: Music Player Application using Tkinter (Python Project)
Libraries used for Music Player Application:
1. Tkinter
2. Pygame module
3. OS module
MusicPlayer Class
1. _init_ Constructor
2. The playsong() Function
3. The stopsong() Function
4. The pausesong() Function
5. The unpausesong() Function
6. Root Window Looping
PART 28: Brick Breaker Game using Tkinter (Python Project)
Prerequisites:
Code for Brick Breaker Game
GameObject class
Ball Class
Paddle Class
Brick Class
Game Class
Complete Code for the Brick Breaker Game:
Brick Breaker Game UI:
PART 29: Calculator Application Using Python Language
What is a Calculator?
Source Code for Calculator Application
Summary:
PART 30: Alarm Clock Using Python Language
Steps on How to Make An Alarm Clock Using Python.
Alarm Clock Using Python With Source Code
Code For Importing Modules
Code For The Module Actual Time
Code For The Module Of Setting The Alarm
Code For The GUI
Complete Source Code of Alarm Clock Using Python
Conclusion
PART 31: Number Guessing Game In Python
Number Guessing Game Rules
Number Guessing Game Implementation in Python Language
PART 32: Python Game : Rock, Paper, Scissors
Rock, Paper, and Scissors Source Code
1. Assign a choice to computer
2. Take input from the player
3. Using while loop to play multiple rounds
4. Display Score
5. Option to play again or quit
Output-
PART 33: Desktop Notifier Application Python Project
What You’ll Discover In This Article
Step 1: Importing Libraries
Step 2: Retrieving the Data From The Web
Step 3: Creating Custom Notification
Source Code for Desktop Notifier Application
Output:
How Can I Turn Off Notifications?
Conclusion
1. 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.
2. wxPython:
This is basically an open-source, cross-platform GUI
toolkit that is written in C++. Also an alternative to
Tkinter.
3. 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.
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.
PART 2: 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.
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.
PART 3: 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.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.
PART 4: 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.
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.
PART 5: 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.
Packing Algorithm:
The steps of Packing algorithm are as follows:
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.
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.
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.
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.
PART 6: 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.
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.
Summary:
In this tutorial, we covered the Tkinter Label Widget which is
used to show text and images in Tkinter GUI application or to
add texts with form input fields like we have done in the
example above.
PART 7: 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.
Summary:
In this tutorial, we learned how to make a Tkinter Button
widget with various options like chaning the style of the
button, adding text to the button or positioning the button. We
also saw a code example for adding an event handler function
to any button to perform some action when the button is
clicked.
PART 8: 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.
Method
Description
Name
invoke()
This method in checkbutton widget is 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.
toggle()
This method in the checkbutton widget is used to toggle between the
different Checkbuttons.
flash()
This method in the checkbutton widget is used to flashed between active
and normal colors.
Summary
So in this tutorial we learned how to create check boxes in a GUI application using
Tkinter checkbutton widget.
PART 9: 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
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
invoke()
This method is generally used to call a function when the state of radio
button gets changed.
flash()
This method is generally used to flash the radio button between its
normal and active colors many times.
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.
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.
Summary:
In this tutorial, we learned about the Radiobutton widget which is used to create
multiple options out of which a single can be selected. This is mainly used when we
create a user form, like registration form.
PART 10: 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.
Summary
In this tutorial, we learned how to use the Tkinter Entry widget
to create a text input field while creating a GUI application.
PART 11: 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.
Summary:
So with this, we have covered the Tkineter Message Widget
which is used to show message in Tkinter GUI application. We
can also create message widget dynamically to show error or
success message in Tkinter application.
PART 12: 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.
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.
Summary:
In this tutorial, we learned how to create a menu for our
Tkinter application and how to add menu items to it and
perform some operation when the user selects any menu items.
PART 13: 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
bg
This option is used to represent the
background color of the widget.
cursor
This option indicates the cursor when the
mouse hovers the menubutton.
This option mainly represents the font
activeforeground 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
direction the specified direction of the button. You
can Use LEFT, RIGHT, or ABOVE to place
the widget accordingly.
disabledforegrou This option indicates the text color of the
nd widget when the widget is disabled
This option indicates the height of the
menubutton. 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.
Option
Description
name
image
This option indicates the image displayed on
the menubutton.
higlightcolor
This option indicates the 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
justify
represented. For left justification, it is set to
LEFT and it is set to RIGHT for the right
justification, and CENTER for the center
justification.
padx
This option indicates the additional padding
of the widget in the horizontal direction.
pady
This option indicates the additional padding
of the widget in the vertical direction.
menu
This option is used to indicate the menu
associated with the menubutton
This option specifies the width of the widget.
width
For 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
Wraplength positive number, the text 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.
text
This option is used to indicate the text on the
widget.
Option
Description
name
A control variable of class StringVar can be
textvariable
associated 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 in the text of the
underline widget which is to be underlined.
The indexing generally starts with zero in
the text.
relief
This option is used to specify the border
type. Its default value is RAISED
Summary:
In this tutorial, we covered the Tkinter Menubutton widget
which is used to create drop-down menus in a Tkinter
application.
PART 14: 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.
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.
Summary:
In this tutorial, we learned about the Tkinter canvas widget
which can be used to draw anything on the canvas, maybe a
chart, and image, or some dynamic shape.
PART 16: Python Tkinter Listbox
Widget
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.
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.
height
This option is used to represents the count of the 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.
Name of Option Description
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 can
selectmode 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.
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.
Summary:
In this tutorial, we learned about the Tkinter Listbox Widget, its basic syntax, the
commonly used methods for the ListBox Widget, and a code example.
PART 17: 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.
Name of the
Description
Option
This option represents the background
activebackground 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
cursor
pointer will be changed to a specific
cursor type and it can be an arrow, dot,
etc.
This option will be set to the procedure
command associated which is called every time the
scrollbar is moved.
Name of the
Description
Option
This option mainly represents the border
elementborderwidt
h width around the arrowheads and the slider.
The default value of this option is -1.
highlightthickness
This option represents the thickness of
the focus highlights
This option indicates the highlight
highlightbackgrou
nd 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. If this option
jump 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 either horizontal
orient 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
takefocus 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
Name of the
Description
Option
repeatinterval The default value of this option is 100
get():
set(first, last):
Summary:
So we have covered the Tkinter Scrollbar widget. It is very
useful where we have a Tkinter application with long lists or
some widget which is too long to fit in the application
window. Then we can use the Scrollbar widget for such
applications.
PART 18: 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.
set(value):
Summary:
In this tutorial, we learned about the Tkinter Scale widget
which is a good UI component for taking numerical input
value within a specific range from the end user.
PART 19: 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.
Summary:
So now we know what a Tkinter Toplevel widget is and how
to create it. The Tkinter Toplevel widget is good to show some
section of your application in a different window which is
displayed on the top of the main application window.
PART 20: 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.
Summary:
So this how a TKinter Spinbox widget works. It is used for
creating input for a specified range of numeric values, which
user can select. If we have a defined range of numbers then its
better to use the Spinbox widget rather than using a Tkinter
Entry widget.
PART 21: 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.
Summary:
So with this we have completed the Tkinter labelframe widget
which is just like HTML fieldset tag, if you know HTML. The
labelframe widget is used to create a border around other
widgets to group other widgets present in your application.
PART 22: 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.
config(options)
This method is mainly used to configure any widget with some
specified options.
Method Name Description
get(startindex,endindex) This method is used to get the text at the specified given range.
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.
Summary:
In this tutorial, we learned about PanedWindow widget which is a great widget if you
want to create multi-column grid like arrangement of widgets in your application.
PART 23: 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.
Method Description
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
Method Description
delete(startindex,endindex)
This method deletes the characters in the specified
range
This method is mainly used to tag the string that is present at the
specified index.
tag_delete(tagname)
To remove the tag from the specified range this method is used.
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.
If you want to destroy this window just click on the Exit button.
Summary:
In this tutorial, we learned Tkinter Text widget which is used when we want to add
a textarea in our application for taking large user inputs.
PART 24: 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.
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.
Summary:
In this tutorial, we learned about the different types of message
boxes that we can create to show information to user or to take
input from users, like to confirm any action, etc. The message
boxes are like pop-ups in which we can show errors, warnings,
etc. to the user.
PART 25: Calculator
Application using Tkinter
(Python Project)
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 everyday lives. Now all the smartphones also have a
Calculator application in them.
While creating any GUI Application there are mainly two
steps:
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().
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.
PART 27: Music Player
Application using Tkinter
(Python Project)
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 on 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
help 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 is 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 the pygame module is:
pip install 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
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 the track
variable and status variable.
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 this:
Prerequisites:
To understand the code to build the brick breaker game in
Python, you should know the following concepts:
1. GameObject
2. Ball
3. Paddle
4. Brick
5. Game
All these classes will have methods to perform various
handling and operations on the respective game element.
Let’s see the code for each class.
GameObject class
This class is the parent class of all the other classes, which
means all the other classes will inherit this class.
The code for this class is as follows:
class GameObject(object):
def __init__(self, canvas, item):
self.canvas = canvas
self.item = item
def get_position(self):
return self.canvas.coords(self.item)
def move(self, x, y):
self.canvas.move(self.item, x, y)
def delete(self):
self.canvas.delete(self.item)
This class has functions to handle the basic lifecycle of
different objects that form the game.
Ball Class
Here is the code for the Ball class:
class Ball(GameObject):
def __init__(self, canvas, x, y):
self.radius = 10
self.direction = [1, -1]
# increase the below value to increase the speed of ball
self.speed = 5
item = canvas.create_oval(x-self.radius, y-self.radius,
x+self.radius, y+self.radius,
fill=‘white’)
super(Ball, self).__init__(canvas, item)
def update(self):
coords = self.get_position()
width = self.canvas.winfo_width()
if coords[0] <= 0 or coords[2] >= width:
self.direction[0] *= -1
if coords[1] <= 0:
self.direction[1] *= -1
x = self.direction[0] * self.speed
y = self.direction[1] * self.speed
self.move(x, y)
def collide(self, game_objects):
coords = self.get_position()
x = (coords[0] + coords[2]) * 0.5
if len(game_objects) > 1:
self.direction[1] *= -1
elif len(game_objects) == 1:
game_object = game_objects[0]
coords = game_object.get_position()
if x > coords[2]:
self.direction[0] = 1
elif x < coords[0]:
self.direction[0] = -1
else:
self.direction[1] *= -1
for game_object in game_objects:
if isinstance(game_object, Brick):
game_object.hit()
In the Ball class the collide() method is used to handle the
collision and is used in the check_collisions() function of the
Game class. Whereas the update() function is to reset the Ball
object after a life is lost and the game starts again.
Paddle Class
Here is the code for the Paddle class:
class Paddle(GameObject):
def __init__(self, canvas, x, y):
# set the shape and position of paddle
self.width = 80
self.height = 10
self.ball = None
item = canvas.create_rectangle(x - self.width / 2,
y - self.height / 2,
x + self.width / 2,
y + self.height / 2,
fill=‘#FFB643’)
super(Paddle, self).__init__(canvas, item)
def set_ball(self, ball):
self.ball = ball
def move(self, offset):
coords = self.get_position()
width = self.canvas.winfo_width()
if coords[0] + offset >= 0 and coords[2] + offset <=
width:
super(Paddle, self).move(offset, 0)
if self.ball is not None:
self.ball.move(offset, 0)
APart from the constructor, the move() method in this class is
important as that enables the movement for the paddle.
Brick Class
Here is the code for the Brick class:
class Brick(GameObject):
COLORS = {1: ‘#4535AA’, 2: ‘#ED639E’, 3: ‘#8FE1A2’}
def __init__(self, canvas, x, y, hits):
self.width = 75
self.height = 20
self.hits = hits
color = Brick.COLORS[hits]
item = canvas.create_rectangle(x - self.width / 2,
y - self.height / 2,
x + self.width / 2,
y + self.height / 2,
fill=color, tags=‘brick’)
super(Brick, self).__init__(canvas, item)
def hit(self):
self.hits -= 1
if self.hits == 0:
self.delete()
else:
self.canvas.itemconfig(self.item,
fill=Brick.COLORS[self.hits])
We start the class definition by setting the colors for the
different brick types. Then in the constructor, the size and
position of the bricks are defined. And then there is
the hit() function that handles whether the brick will disappear
or it will take the hit and change color to take the next hit.
Game Class
This is the main class that controls everything. Here is the
code:
class Game(tk.Frame):
def __init__(self, master):
super(Game, self).__init__(master)
self.lives = 3
self.width = 610
self.height = 400
self.canvas = tk.Canvas(self, bg=‘#D6D1F5’,
width=self.width,
height=self.height,)
self.canvas.pack()
self.pack()
self.items = {}
self.ball = None
self.paddle = Paddle(self.canvas, self.width/2, 326)
self.items[self.paddle.item] = self.paddle
# adding brick with different hit capacities - 3,2 and 1
for x in range(5, self.width - 5, 75):
self.add_brick(x + 37.5, 50, 3)
self.add_brick(x + 37.5, 70, 2)
self.add_brick(x + 37.5, 90, 1)
self.hud = None
self.setup_game()
self.canvas.focus_set()
self.canvas.bind(‘<Left>’,
lambda _: self.paddle.move(-10))
self.canvas.bind(‘<Right>’,
lambda _: self.paddle.move(10))
def setup_game(self):
self.add_ball()
self.update_lives_text()
self.text = self.draw_text(300, 200,
‘Press Space to start’)
self.canvas.bind(‘<space>’, lambda _:
self.start_game())
def add_ball(self):
if self.ball is not None:
self.ball.delete()
paddle_coords = self.paddle.get_position()
x = (paddle_coords[0] + paddle_coords[2]) * 0.5
self.ball = Ball(self.canvas, x, 310)
self.paddle.set_ball(self.ball)
def add_brick(self, x, y, hits):
brick = Brick(self.canvas, x, y, hits)
self.items[brick.item] = brick
def draw_text(self, x, y, text, size=‘40’):
font = (‘Forte’, size)
return self.canvas.create_text(x, y, text=text,
font=font)
def update_lives_text(self):
text = ‘Lives: %s’ % self.lives
if self.hud is None:
self.hud = self.draw_text(50, 20, text, 15)
else:
self.canvas.itemconfig(self.hud, text=text)
def start_game(self):
self.canvas.unbind(‘<space>’)
self.canvas.delete(self.text)
self.paddle.ball = None
self.game_loop()
def game_loop(self):
self.check_collisions()
num_bricks = len(self.canvas.find_withtag(‘brick’))
if num_bricks == 0:
self.ball.speed = None
self.draw_text(300, 200, ‘You win! You the Breaker of
Bricks.’)
elif self.ball.get_position()[3] >= self.height:
self.ball.speed = None
self.lives -= 1
if self.lives < 0:
self.draw_text(300, 200, ‘You Lose! Game Over!’)
else:
self.after(1000, self.setup_game)
else:
self.ball.update()
self.after(50, self.game_loop)
def check_collisions(self):
ball_coords = self.ball.get_position()
items = self.canvas.find_overlapping(*ball_coords)
objects = [self.items[x] for x in items if x in self.items]
self.ball.collide(objects)
In this class, we have the following:
And with that, this tutorial ends. Hope the game works fine for
you. We recommend you to edit and customize the code to
make the game better. Try to add more features to the game.
PART 29: Calculator
Application Using Python
Language
The Calculator is one application that we all utilize in our day-
to-day lives. If you are attempting to get your hands dirty with
programming in python, Calculator is a straightforward and
helpful project at the same time. Today, we will develop
a Python Calculator using Tkinter with simple to follow
instructions.
Here is how our calculator will appear, which is created using
the input field, buttons, and logic defined in functions for
calculation purposes. For example, if you want to add two
numbers, there must be logic for addition, similarly for
subtraction, multiplication, and so on, we have created
functions whose task is to perform these operations.
We have an Input Field where the user input will be shown
along with the calculation’s ultimate result.
The buttons are numbered 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, -, *, /, =,
and C. (clear button)
What is a Calculator?
For those unfamiliar, a calculator is a computer application
that mimics the behaviour of any hand-held calculator used for
completing mathematical calculations. It is a really simple
item that we use on a daily basis. A Calculator application is
now available on all cellphones.
There are primarily two processes involved in developing any
GUI application:
Creating a User Interface is the initial stage.
The second and most crucial stage is to provide the
functionality to the graphical user interface.
Let’s get started by making a simple calculator app in Python
utilizing Tkinter for basic arithmetic calculations.
4. Display Score
computer_win=0
player_win=0
player_win and computer_win are initialised at 0. These
variables will store the scores.
Output-
Here we have played four rounds with the computer. After
each round scores are printed for the player and computer.
Chose Rock, Paper, Scissors?Rock
Tie!
Score
computer win: 0
player win: 0
do you wish to continue(y/n)y
Score
computer win: 1
player win: 0
Tie!
Score
computer win: 1
player win: 0
Score
computer win: 1
player win: 1
Output:
Conclusion
This program is compatible with any operating system,
including Windows, Linux, and Mac. Please feel free to ask in
the comments area of this post if you desire a simpler desktop
notification program.