Python Project
Python Project
Tkinter
35
Mini projects
practical guide for Begineers
VAISHALI B. BHAGAT
ISBN - Paperback:9798883772695
For
My Father
CONTENTS
2
1. Simple Tkinter Application to Show a Welcome
Message
8
2. Simple Grade Display GUI
15
3. Simple Abecedarian Series Generator
Application
20
4. Simple Character Occurrence Counter
Application
24
5. Simple GCD and LCM Calculator
29
6. Battery Level Monitor and Status Alert GUI
39
7. Simple Color Changer Application
44
8. Secure Download Manager
49
9. Simple OTP Generator
53
10. Simple BMI Calculator
58
11. Decimal to Binary, Octal and Hexadecimal
Convertor
12. Simple ListBox Movement Application 63
76
13. Simple Font Style Customizer
85
14. Image Swapper Application
92
15. Simple Progress Bar Application
97
16. Times Table Generator
104
17. Simple ShapeDrawer Application
112
18. Simple WebPage Viewer
116
19. Word Sorter Program
121
20. Bank Account Simulator
127
21. Yearly Calender Design Program
132
22. Captcha Generator and Verifier
141
23. Book QR Code Generator
148
24. Book barcode generator
153
25. Currency converter
159
26. Simple and Compound Interest
166
27. Word to PDF Converter
177
28. Image Zoomer Application
188
29. Simple GUI Calculator
198
30. Age calculator
203
31. Stopwatch and Date Display
208
32. Drag and Drop Application
213
33. Traffic Signal Simulator
218
34. Secure Password Validator
228
35. Email Login System with Dynamic Account
Creation
ACKNOWLEDGMENTS
Vaishali B.Bhagat
Simple Tkinter Application to Show a
Welcome Message
Project #1
Creating a Tkinter App to Show a Welcome Message
Introduction:
Welcome to our Tkinter tutorial! In this program, we'll explore how to
make a simple graphical user interface (GUI) using Python Tkinter.
Our aim is to build a program that greets users with a welcome
message when they click a button. To do this, we'll be using Tkinter,
the most popular library for making GUIs in Python. We'll use two
widgets: a Button labeled "Click Me" and a Label to display the text.
Initially, the label won't show any text. However, when the button is
clicked, it will update to show the message "Welcome to Python
Programming world!" in a bold font. Let's dive in and create our first
Tkinter app!
Requirements:
Text Editor or IDE: You'll need a text editor to write the code. I've
used the Thonny IDE for writing and executing this program.
However, you can use any Python IDE or text editor of your choice to
run the program.
Python with Tkinter: Ensure that you have Python installed on your
system. Tkinter is usually included with Python installations by
default, so there's typically no separate installation needed. It's
assumed that you have a basic understanding of Python
programming language concepts such as functions, variables, and
control flow. We won't go deeply into these topics in this book.
Tkinter Widgets: We'll use two Tkinter widgets to design the GUI:
Label and Button.
Label widget:
Label widget is GUI element to display static text or image on Tkinter
window. They are specially used for displaying information,
instruction and non edited text. We can also use them for displaying
heading on window. They can display text in different fonts, sizes,
and colors. Labels can also display images. They do not accept user
input.
Label Widget Parameters:
text: Specifies the text displayed on the label.
bg: Specifies the background color of the label.
fg: Specifies the foreground (text) color of the label.
width: Specifies the width of the label (in characters or pixels).
height: Specifies the height of the label (in characters or pixels).
font: Specifies the font used for the label text.
relief: Specifies the appearance of the label border (e.g., tk.FLAT,
tk.SUNKEN, tk.RAISED). The default value is FLAT.
anchor: Specifies the exact position of the text for the label content
(e.g., tk.N, tk.W, tk.CENTER)
Button Widget:
Buttons are interactive elements that users can click to perform
actions or triggers events. They are used to create clickable buttons
on Tkinter window.
Button Widget Parameters:
text: Specifies the text displayed on the button.
Command: Sets to the function call when function is called
bg: Specifies the background color of the button.
fg: Specifies the foreground (text) color of the button.
width: Specifies the width of the button(in characters or pixels).
height: Specifies the height of the button(in characters or pixels).
font: Specifies the font used for the button text.
relief: Specifies the appearance of the button border (e.g., tk.FLAT,
tk.SUNKEN, tk.RAISED). The default value is FLAT.
anchor: Specifies the exact position of the text for the label content
(e.g., tk.N, tk.W, tk.CENTER)
Label and button widgets have more parameters than those
explained above. We will discuss them in detail later.
To create a button and label widget using Tkinter in Python, you can
follow these steps:
Create a Label Widget
1. First, you need to import the Tkinter module. Typically, you
import it as tk for easier reference.
import tkinter as tk
2. Create the main window using the Tk() constructor.
root = tk.Tk()
3. Create a label widget using the Label() constructor.
Specify the parent widget (in this case, the main window
root), along with any optional parameters like text or font.
label = tk.Label(root, text="Hello, World!")
4. Use the pack() method to pack the label widget into the
main window. This makes it visible within the window.
label.pack()
2. Pack the button widget into the main window using the
pack() method.
button.pack()
root.mainloop()
Solutions:
import tkinter as tk
# Create the main Tkinter window
root = tk.Tk()
# Set the title of the window
root.title("Welcome Message !!!")
# Define a bold font for the label
bold_font = ("Arial", 15, "bold")
# Creating a button with a command to update the label text
button = tk.Button(root, text="Click Me", command=lambda:
welcome_label.config(text="Welcome to Python Programming
world!"))
button.pack() # Place the button in the window
# Creating a label with an empty text and the specified bold font
welcome_label = tk.Label(root, text="", font=bold_font)
welcome_label.pack() # Place the label in the window
# Start the Tkinter event loop
root.mainloop()
Output:
After running the provided code, you'll see a graphical user interface
(GUI) window displayed on your screen.
After clicking the ‘Click Me’ button, following window is displayed on
your screen.
Simple Grade Display GUI
Project #2
Design a Simple GUI using Tkinter in Python to display
grades. The grades assigned to the students of a certain
engineering college are O, A, B, C, F. Write a program
that prompts the users to enter a character O, A, B, C, F
and display their grades as Outstanding, Very Good,
Good, Average, and Fail respectively using if-elif-else.
Introduction:
In this program, we'll design a simple Graphical User Interface (GUI)
using Tkinter to display grades. As you know, Tkinter is a popular
Python library for building desktop applications. Our goal is to design
an application that allows users to input their grades and displays the
corresponding grade descriptions.
In many educational institutions, grades are represented by letters
such as O (Outstanding), A (Very Good), B (Good), C (Average), and
F (Fail). Our program will prompt users to enter one of these
characters, and based on their input, it will provide the corresponding
grade description.
We’ll create simple graphical user interface where users can easily
input their grades and view the corresponding descriptions. We'll
utilize the if-elif-else statement in Python to handle the logic of
determining the grade description based on the user's input.
By the end of this program, you'll be able to build a simple GUI
application with Tkinter and applying conditional logic to provide
useful feedback to users based on their input. Let's get started!
Requirement:
We will use the same widgets (Labels and Buttons) that were
discussed in our previous programs. Additionally, we'll introduce a
new widget: the Entry widget. We'll discuss its functionality and
usage as we proceed with the program.
Entry widget:
The Entry widget in Tkinter is used to create a single-line text entry
field where users can input text or numbers. It allows users to type
text or numbers directly into the GUI application. The Entry widget is
commonly used in Tkinter applications for accepting user input, such
as usernames, passwords, search queries, or any other type of
textual data entry.
Tkinter Entry Widget Properties:
Text Variable (textvariable): Associates a Tkinter variable with the
Entry widget, allowing you to set or retrieve the text content
dynamically.
Width (width): Sets the width of the entry field in characters.
Background (bg): Sets the background color of the entry field.
Foreground (fg): Sets the text color of the entry field.
Font (font): Sets the font style and size for the text in the entry field.
Border Width (borderwidth): Sets the width of the border around
the entry field.
Relief: Determines the appearance of the border. It can be set to
"flat", "raised", "sunken", "groove", or "ridge".
State: Sets the state of the entry field. It can be set to "normal",
"readonly", or "disabled".
Insert Background (insertbackground): Sets the color of the
insertion cursor (the blinking vertical bar).
xscrollcommand: Attaches a scrollbar for horizontal scrolling.
insertwidth: Defines the insertion cursor width (default: 3 pixels).
readonlybackground: Sets the background color for read-only
mode.
invalidcommand: Triggers a function when invalid input occurs.
Solutions:
import tkinter as tk
def display_grade():
# Get user input from the entry widget and convert it to uppercase
user_input = entry.get().upper()
# Check the user input and display the corresponding grade
description
if user_input == 'O':
result_label.config(text="Outstanding")
elif user_input == 'A':
result_label.config(text="Very Good")
elif user_input == 'B':
result_label.config(text="Good")
elif user_input == 'C':
result_label.config(text="Average")
elif user_input == 'F':
result_label.config(text="Fail")
else:
# Display an error message for invalid grades
result_label.config(text="Invalid Grade")
# Create the main window
root = tk.Tk()
root.title("Grade Display Program")
# Create and place widgets
# Label to instruct the user to enter a grade
label = tk.Label(root, text="Enter Grade (O, A, B, C, F):")
label.pack(pady=10)
# Entry widget for user to input a grade
entry = tk.Entry(root)
entry.pack(pady=10)
# Button to submit the grade and trigger the display_grade function
submit_button = tk.Button(root, text="Submit",
command=display_grade)
submit_button.pack(pady=10)
# Label to display the result or error message based on the entered
grade
result_label = tk.Label(root, text="")
result_label.pack(pady=10)
# Start the Tkinter event loop
root.mainloop()
Output:
After running the provided code, you'll see a graphical user interface
(GUI) window displayed on your screen.
After entering grade A in the entry field, the window displays the
grade description, indicating that A is very good.
After entering grade O in the entry field, the window displays the
grade description, indicating that O is Outstanding
Simple Abecedarian Series Generator
Application
Project #3
Abecedarian refers to a series or list in which the
elements appear in alphabetical order. Design a simple
Python GUI form using Tkinter to generate Abecedarian
series.
Introduction:
In this program, we will design a simple GUI form to generate
Abecedarian series. An Abecedarian series, as the name suggests,
arranges elements in alphabetical order. Our goal is to create a
simple graphical user interface (GUI) that takes two strings as input
and generates an Abecedarian series based on these inputs.
For example, if str1 is "ABCDEF" and str2 is "ate", the program will
output an Abecedarian series starting with "Aate", followed by
"Bate", "Cate", "Date", "Eate", and "Fate".
This program will provide a user-friendly interface where users can
input their desired strings and receive the corresponding
Abecedarian series as output. Let's dive into the code and explore
how this program works!
Solutions:
import tkinter as tk
def generate_abecedarian_series():
# Get user input strings from entry widgets
str1 = entry_str1.get()
str2 = entry_str2.get()
# Check if both input strings are non-empty
if str1 and str2:
result = ""
# Iterate through each character in str1
for char in str1:
# Concatenate each character of str1 with str2 and add a
space
result += char + str2 + " "
# Update the result_label with the current result
result_label.config(text=result)
else:
# Display an error message if either input string is empty
result_label.config(text="Both input strings are required.")
# Create the main window
root = tk.Tk()
root.title("Abecedarian Series Generator")
# Create and place widgets
# Label to instruct the user to enter a first string
label_str1 = tk.Label(root, text="Enter String 1:")
label_str1.pack(pady=5)
# Entry widget for user to input a first string
entry_str1 = tk.Entry(root)
entry_str1.pack(pady=5)
# Label to instruct the user to enter a second string
label_str2 = tk.Label(root, text="Enter String 2:")
label_str2.pack(pady=5)
# Entry widget for user to input a second string
entry_str2 = tk.Entry(root)
entry_str2.pack(pady=5)
# Button to generate Abecedarian Series
generate_button = tk.Button(root, text="Generate Abecedarian
Series", command=generate_abecedarian_series)
generate_button.pack(pady=10)
# Label to display the result
result_label = tk.Label(root, text="")
result_label.pack(pady=10)
# Start the Tkinter event loop
root.mainloop()
Output:
After running the above code, the following GUI will be displayed on
your screen. If the user does not enter both String 1 and String 2, a
message saying 'Both input strings are required' will be displayed on
the main window.
If the user enters String 1 and String 2 properly, the following window
will display the appropriate output on the main window.
Simple Character Occurrence Counter
Application
Project #4
Design a simple GUI form using Tkinter to count and
print the number of occurrences of each character in a
dictionary.
Introduction:
In this Program, we’ll make a simple GUI form to count characters.
Our goal is to create a form where you can type in some text, click a
button, and see how many times each letter appears. Counting
characters is important for many text tasks. With Tkinter, we'll make
a form that's easy to use. You'll be able to type in your text and get
the count with just one click. We'll use Entry widget for typing, Button
widget for counting, and Python dictionaries to keep track of the
counts. If you've followed our previous programs, you'll know about
labels, entry fields, and buttons already. Now, let's build this helpful
form together!
Solutions:
import tkinter as tk
def count_occurrences():
# Get user input from the entry widget
user_input = entry.get()
# Count occurrences of each character in the input string
char_count = {} # Initialize an empty dictionary to store the count
of occurrences for each character
# Iterate through each character in the user_input string
for char in user_input:
# Check if the character is already in the dictionary, if not,
default to 0
current_count = char_count.get(char, 0)
# Increment the count for the current character
char_count[char] = current_count + 1
# Display the result in the label
result_label.config(text=str(char_count))
# Create the main window
root = tk.Tk()
root.title("Character Occurrence Counter")
# Create and place widgets
label = tk.Label(root, text="Enter a message:")
label.pack(pady=10)
entry = tk.Entry(root)
entry.pack(pady=10)
count_button = tk.Button(root, text="Count Occurrences",
command=count_occurrences)
count_button.pack(pady=10)
result_label = tk.Label(root, text="")
result_label.pack(pady=10)
# Start the Tkinter event loop
root.mainloop()
Output :
After running above code, following GUI will be displayed on your
screen.
This program creates a simple GUI form using Tkinter. It consists of
a label prompting the user to enter a string, an entry field to input the
string, and a button to trigger the character counting process. The
count_occurrences () function is called when the button is clicked. It
retrieves the input string from the entry field, iterates over each
character in the string, and counts the occurrences of each character
using a dictionary. Finally, it prints the dictionary containing the
character counts.
Simple GCD and LCM Calculator
Project#5
Create a graphical user interface (GUI) application using
Tkinter in Python for calculating both the Greatest
Common Divisor (GCD) and the Least Common Multiple
(LCM) of two given integers entered by the user.
Introduction:
Welcome to our Tkinter application! Today, we'll be building a
graphical user interface (GUI) to calculate both the Greatest
Common Divisor (GCD) and the Least Common Multiple (LCM) of
two integers. These calculations are common in mathematics and
are often needed in various applications. With Tkinter, we'll create a
simple and easy-to-use interface. Users can enter two integers, and
with a click of a button, they'll get the calculated GCD and LCM
displayed in a messagebox. This application will be helpful for
anyone who needs to find the GCD and LCM quickly without using a
calculator or performing manual calculations. So, let's dive in and
create this handy tool together!
Solution:
import tkinter as tk
from tkinter import messagebox
def gcd(a, b):
# Continuously loop until b becomes zero
while b != 0:
# Store the current value of b in a temporary variable c
c=b
# Update the value of b to be the remainder of a divided by the
current value of b
b=a%b
# Assign the original value of b (stored in c) to a, effectively
swapping the values
a=c
# When b becomes zero, return the current value of a, which is
the GCD
return a
def calculate():
try:
# Attempt to retrieve the values entered in the entry fields and
convert them to integers
num1 = int(entry_num1.get())
num2 = int(entry_num2.get())
# Calculate the GCD using the previously defined gcd function
result = gcd(num1, num2)
# Calculate the LCM using the formula: LCM = (num1 * num2)
/ GCD
lcm = (num1 * num2) / result
# Display the result in a message box, including both the GCD
and LCM
messagebox.showinfo("Result", f"The GCD of {num1} and
{num2} is {result}\n "f"The LCM of {num1} and {num2} is {lcm}")
except ValueError:
# If the user entered invalid input (e.g., non-integer values),
display an error message
messagebox.showerror("Error", "Please enter valid integers for
both numbers.")
# Creating the main tkinter window
root = tk.Tk()
root.title("GCD and LCM Calculator")
# Setting font for title label
bold_font = ("Arial", 20, "bold")
# Creating label for title
title_label = tk.Label(root, text="GCD and LCM Calculator",
bg="white", fg="Green", font=bold_font)
title_label.pack()
# Creating labels and entry fields
label_num1 = tk.Label(root, text="Enter first number:")
label_num1.pack(padx=5, pady=5)
entry_num1 = tk.Entry(root)
entry_num1.pack(padx=5, pady=5)
label_num2 = tk.Label(root, text="Enter second number:")
label_num2.pack(padx=5, pady=5)
entry_num2 = tk.Entry(root)
entry_num2.pack(padx=5, pady=5)
# Creating a button to trigger calculation
calculate_button = tk.Button(root, text="Calculate GCD And LCM",
command=calculate)
calculate_button.pack(padx=5, pady=5)
# Running the main tkinter event loop
root.mainloop()
Output:
After running the provided code, you'll see a graphical user interface
(GUI) window displayed on your screen.
After clicking on the 'Calculate GCD and LCM' button, the program
displays a messagebox showing the calculated GCD (Greatest
Common Divisor) and LCM (Least Common Multiple) of the input
numbers.
Battery Level Monitor and Status Alert GUI
Project #6
Design a graphical user interface (GUI) application using
Tkinter in Python to monitor battery levels and display
alerts when the battery level is low.
Introduction:
In this program, we will design a simple GUI to monitor battery levels
and receive alert message when the battery level is low. Our goal is
to develop an application that monitors battery levels and issues
alerts when the battery level is low, all triggered by the click of a
button. Battery monitoring and alerting are essential functionalities,
especially in systems that rely on battery power, such as laptops,
smartphones, and IoT devices. With Tkinter, we'll create an intuitive
interface where users can easily check the current battery level and
receive timely alerts when the battery is running low. We wil use
different type of message boxes to keep you inform about your
device power status.
Requirement:
We will use button widget and messagebox to design this simple
GUI form. Lets talk about different types of messagebox and use
them in code.
Messagebox :
Tkinter provides a convenient module called messagebox to create
different types of message boxes within your GUI applications.
These boxes are useful for displaying information, warnings, errors,
and even asking questions to users.
Informative Boxes:
showinfo(title, message, **options): Displays a message box with an
information icon.
showwarning(title, message, **options): Displays a message box
with a warning icon.
showerror(title, message, **options): Displays a message box with
an error icon.
Asking Questions:
askquestion(title, message, **options): Displays a message box with
"Yes" and "No" buttons. Returns either 'yes' or 'no'.
askokcancel(title, message, **options): Displays a message box with
"OK" and "Cancel" buttons. Returns either 'ok' or 'cancel'.
askyesno(title, message, **options): Displays a message box with
"Yes" and "No" buttons. Returns either True for "Yes" or False for
"No".
askretrycancel(title, message, **options): Displays a message box
with "Retry", "Cancel", and "Ignore" buttons. Returns either 'retry',
'cancel', or 'ignore'.
Common Options:
default: Sets the default button (e.g., 'ok', 'yes').
icon: Specifies the icon to display (e.g., 'info', 'warning', 'error').
parent: Defines the parent window of the message box.
How to create messagebox?
First, import the messagebox module from Tkinter.
from tkinter import messagebox
Show Information Message Box: Use the showinfo() function to
display an information message box.
messagebox.showinfo("Title", "This is an information message.")
Show Warning Message Box: Use the showwarning() function to
display a warning message box. Here's how you can use it:
Code:
messagebox.showwarning("Warning", "This is a warning message.")
Ask for Yes, No, or Cancel: Use the askyesnocancel() function to ask
for a yes, no, or cancel response. Here's how you can use it
Code:
result = messagebox.askyesnocancel("Question", "Do you want to
save changes?")
if result is True:
# User clicked Yes
pass
elif result is False:
# User clicked No
pass
else:
# User clicked Cancel
Pass
Show askretrycancel Messagebox : Use askretrycancel() function
to ask the user whether to retry an operation or cancel it. It returns
True if the user chooses to retry and False if the user chooses to
cancel. Here's how you can use it:
Code:
result = messagebox.askretrycancel("Retry or Cancel", "An error
occurred. Do you want to retry?")
if result:
print("User chose to retry.")
else:
print("User chose to cancel.")
Solutions:
import tkinter as tk
from tkinter import messagebox
# Function to check the battery level and display appropriate
messages
def check_battery_level():
# Dummy battery level for testing
battery_level = 10
# Check if battery level is low
if battery_level < 20:
# Display warning message about low battery
messagebox.showwarning("Low Battery", "Battery level is low!
Please plug in")
# Ask user if they want to continue
response = messagebox.askyesno("Yes/No", "Do you want to
continue?")
# If user chooses No or closes the messagebox, abort the
operation
if not response:
messagebox.showinfo("Info", "Operation aborted.")
return
# If user chooses Yes, or battery level is above 20%, continue the
operation
messagebox.showinfo("Info", "Operation continues...")
# Create the main Tkinter window
root = tk.Tk()
root.title("Battery Level Alert")
# Create a button to trigger battery level checking
check_button = tk.Button(root, text="Check Battery Level",
command=check_battery_level)
check_button.pack()
# Start the Tkinter event loop
root.mainloop()
Output :
After running the provided code, you'll see a graphical user interface
(GUI) window displayed on your screen.
Introduction:
In this problem, we’ll design and implement a Graphical User
Interface (GUI) application using Tkinter in Python. Our objective is
to create an application that allows users to dynamically change the
background color of a form by clicking on color buttons.
Dynamic background color changing is a common feature in GUI
applications. It provide users with customization options to
personalize their interface experience. With Tkinter, we'll build an
intuitive interface where users can interact with color buttons to
modify the background color of the form in real-time.
Solutions:
import tkinter as tk
# Create the main window
root = tk.Tk()
root.title("Color Changer")
# Define a bold font style and font name for color_label
bold_font = ("Arial", 12, "bold")
# Create a label to provide instructions
color_label = tk.Label(root, text="Click a color button to change the
form color",bg = 'white',font = bold_font)
color_label.pack(pady=40)
# Create a frame to contain color buttons
color_frame = tk.Frame(root, padx=10, pady=10)
color_frame.pack()
# Define a bold font style
bold_font = ("Times new Roman", 10, "bold")
# Create color buttons, each changing the background color when
clicked
redButton = tk.Button(color_frame, text='Red', bg='red', padx=5,
pady=5, command=lambda: root.config(bg='red'),font = bold_font)
greenButton = tk.Button(color_frame, text='Green', bg='green',
padx=5, pady=5, command=lambda: root.config(bg='green'),font =
bold_font)
blueButton = tk.Button(color_frame, text='Blue', bg='blue', padx=5,
pady=5, command=lambda: root.config(bg='blue'),font = bold_font)
yellowButton = tk.Button(color_frame, text='Yellow', bg='yellow',
padx=5, pady=5, command=lambda: root.config(bg='yellow'),font =
bold_font)
pinkButton = tk.Button(color_frame, text='Pink', bg='pink', padx=5,
pady=5, command=lambda: root.config(bg='pink'),font = bold_font)
brownButton = tk.Button(color_frame, text='Brown', bg='brown',
padx=5, pady=5, command=lambda: root.config(bg='brown'),font =
bold_font)
orangeButton = tk.Button(color_frame, text='Orange', bg='orange',
padx=5, pady=5, command=lambda: root.config(bg='orange'),font =
bold_font)
# Pack buttons into the frame, placing them in one line horizontally
redButton.pack(side='left')
greenButton.pack(side='left')
blueButton.pack(side='left')
yellowButton.pack(side='left')
pinkButton.pack(side='left')
brownButton.pack(side='left')
orangeButton.pack(side='left')
# Start the Tkinter event loop
root.mainloop()
Output:
After executing the provided code, a graphical user interface (GUI)
window will appear on your screen. This GUI window serves as the
interface for the Dynamic Background Color Changer application.
Here's what you'll see:
Title: Positioned at the top of the window, you'll find a title reading
"Color Changer". This title indicates the purpose of the application.
Label: Beneath the form title, there is an instructional label that
reads, "Click a color button to change the form color."
Color Buttons: Below the title, there are seven color buttons: Red,
Green, Blue, Yellow, Pink, Brown, and Orange. These buttons allow
you to select the desired background color for the form.
Form: The main area of the window serves as the form, where the
background color dynamically changes according to the color button
you click.
When the user clicks on the Yellow button, the background of the
window changes to yellow, as shown in the output.
After clicking on the Green button, the window's background
changes to green, as demonstrated in the output.
Secure Download Manager
Project #8
Develop a Graphical User Interface (GUI) application
using Tkinter in Python to facilitate the downloading of
files from the internet.
Introduction:
Downloading files from the internet is something many of us do
regularly, but it's important to be cautious because there can be risks
like viruses or malware hiding in those files. With Tkinter, we'll create
a simple program that warns users about these risks before they
start downloading. We'll use buttons and message boxes to make it
easy to understand and interact with. This program will help users
make informed decisions about downloading files, keeping their
devices safe from potential threats. Let's work together to build this
user-friendly and security-conscious program!
Requirement:
In our previous program, we learned about different types of
message boxes and how they work. In this program, we'll use
Tkinter's showinfo and showwarning message boxes to warn users
about the security risks of downloading files from the internet. We'll
also add a button to start the download process. When users click
the download button, the program will give them helpful messages
about the security risks before starting the download. This way,
users can make smart decisions about their online safety.
Solutions:
import tkinter as tk
from tkinter import messagebox
# Function to show the warning message before downloading the file
def show_download_warning():
# Prompt a warning message using messagebox
messagebox.showwarning( "Warning", " Suspicious File is
downloading ...........")
response = messagebox.askokcancel("Virus Detected",
"Downloading files from the internet can be unsafe. Do you want to
continue?")
# If the user chooses to continue, continue the operation
if response:
messagebox.showinfo("Download", "File download complete!")
# If the user chooses to cancel, cancel the operation
else:
messagebox.showinfo("Cancelled", "File download
cancelled.")
# Create the main Tkinter window
root = tk.Tk()
root.title("File Download")
# Create a button to trigger the download warning message
download_button = tk.Button(root, text="Download File",
command=show_download_warning)
download_button.pack() #pack the button into window
# Start the tkinter event loop
root.mainloop()
Output:
Upon executing the code, following GUI window is displayed
Solutions:
import tkinter as tk
from PIL import Image, ImageTk
# Define current_image_index variable
current_image_index = 0
def swap_images():
# Use the global keyword to access and modify the global
variable current_image_index
global current_image_index
# Update the current_image_index to the index of the next image
in the images list
current_image_index = (current_image_index + 1) % len(images)
# Swap the positions of the images in the images list
images[0], images[1] = images[1], images[0]
# Update the image_label to display the first image in the list
image_label.config(image=images[0])
# Update the image_label2 to display the second image in the list
image_label2.config(image=images[1])
# Create a Tkinter window
root = tk.Tk()
# Set the title of the window to "Image Swapper"
root.title("Image Swapper")
# List of image file paths
image_files = ["image/image1.jpg", "image/image2.jpg"]
# Initialize an empty list to store resized and converted images
images = []
# Iterate over each image file path
for file in image_files:
# Open the image file and resize it to the desired dimensions
(200x200 pixels)
img = Image.open(file).resize((200, 200), Image.ANTIALIAS)
# Convert the resized image to a Tkinter PhotoImage object
photo_img = ImageTk.PhotoImage(img)
# Append the PhotoImage object to the images list
images.append(photo_img)
# Display original images
# Create a Label widget to display the first image
image_label = tk.Label(root, image=images[0])
# Place the image_label widget in the Tkinter window using the grid
geometry manager
# The widget is placed in row 0 and column 0
image_label.grid(row=0, column=0)
# Create another Label widget to display the second image
image_label2 = tk.Label(root, image=images[1])
# Place the image_label2 widget in the Tkinter window using the grid
geometry manager
# The widget is placed in row 0 and column 1
image_label2.grid(row=0, column=1)
# Create a button widget for swapping images
swap_button = tk.Button(root, text="Swap Image",
command=swap_images)
# Place the button in the Tkinter window using the grid geometry
manager
# The button will be placed in row 1 and will span across 2 columns
swap_button.grid(row=1, columnspan=2)
When the user clicks on the "Start Progress" button, the progress
bar begins processing.
Solutions:
import tkinter as tk
# Function to generate the times table
def generate_times_table():
try:
# Get the number entered by the user
number = int(number_entry.get())
# Enable the text area for editing and clear its contents
text_area.config(state=tk.NORMAL)
text_area.delete("1.0", tk.END)
# Generate and display the times table for the entered number
# Iterate through numbers from 1 to 10 to generate the times
table for the entered number
for i in range(1, 11):
# Calculate the result of multiplying the entered number by the
current iteration value
result = number * i
# Insert the result into the text area at the end of the current
content
text_area.insert(tk.END, f"{number} x {i} = {result}\n")
# Disable the text area to prevent editing
text_area.config(state=tk.DISABLED)
except ValueError:
# If the entered value is not a valid integer, display an error
message
text_area.config(state=tk.NORMAL)
# Clear the contents of the text area from the first character of
the first line to the end of the text
text_area.delete("1.0", tk.END)
# Insert a message prompting the user to enter a valid number
at the end of the text area
text_area.insert(tk.END, "Please enter a valid number.")
# Disable the text area to prevent editing
text_area.config(state=tk.DISABLED)
# Create the main window
window = tk.Tk()
window.title("Times Table Generator")
# Create and place widgets
tk.Label(window, text="Enter a number:").pack(pady=5)
number_entry = tk.Entry(window)
number_entry.pack(pady=5)
generate_button = tk.Button(window, text="Generate Times Table",
command=generate_times_table)
generate_button.pack(pady=10)
# Create a textarea (text widget)
text_area = tk.Text(window, height=10, width=40)
text_area.pack(padx=10, pady=10)
# Start the GUI event loop
window.mainloop()
Output:
After executing the above code, you will see a graphical user
interface (GUI) window appear on your screen. At the top of the
window, there's an input field where users can enter a number for
which they want to generate the times table. Below the input field,
there's a 'Generate' button. Users click this button to initiate the
generation of the times table based on the number entered in the
input field. Beneath the 'Generate' button, there's a text area. Once
the user clicks the 'Generate' button, the times table for the entered
number will be displayed in this text area.
Simple ShapeDrawer Application
Project #17
Develop a Python program called ShapeDrawer that
allows users to interactively select and display various
shapes on a canvas.
Introduction:
Welcome to ShapeDrawer! This program is designed to help you
explore various shapes interactively. On the main window, you'll find
six different radio buttons representing different shapes: square,
rectangle, circle, triangle, and diamond,pentagon.
With ShapeDrawer, you can select any shape you want to draw on
the canvas. Once you've made your selection, simply click the
"Display Shape" button, and voila! The chosen shape will be
displayed dynamically on the canvas area.
Using radio buttons makes it easy for you to choose the shape you
want to draw, and the "Display Shape" button ensures that your
canvas stays clutter-free by clearing any previously drawn shapes
before displaying the new one.
Canvas
In Tkinter, a canvas is like a blank sheet of paper where you can
draw shapes, lines, and images. It's a space where you can create
and display graphical elements.
Think of it as a drawing board where you can use your imagination to
create anything you want. You can draw shapes like squares, circles,
and triangles, or even make your own designs.
A canvas is useful for creating interactive graphics, such as games
or diagrams. You can add different elements to the canvas and make
them move or change based on user input.
Overall, a canvas in Tkinter is a versatile tool that allows you to
create and display visual content in your Python applications.
In Tkinter, the Canvas widget is used to create a drawing area where
you can display and manipulate graphical elements such as shapes,
lines, and images.
Here are some common properties of the Canvas widget that you
can modify:
bg (background): Sets the background color of the canvas.
width: Sets the width of the canvas in pixels.
height: Sets the height of the canvas in pixels.
bd (borderwidth): Sets the width of the border around the canvas.
relief: Sets the border style of the canvas. It can be set to "flat"
(default), "raised", "sunken", "ridge", or "groove".
scrollregion: Sets the region of the canvas that can be scrolled. It
should be specified as a tuple (x1, y1, x2, y2) representing the
coordinates of the top-left and bottom-right corners of the region.
highlightbackground: Sets the color of the focus highlight when the
canvas does not have focus.
highlightcolor: Sets the color of the focus highlight when the
canvas has focus.
highlightthickness: Sets the width of the focus highlight.
cursor: Sets the cursor type when the mouse is over the canvas. It
can be set to "arrow", "circle", "cross", "hand2", "fleur", and more.
These properties allow you to customize the appearance and
behavior of the canvas in your Tkinter applications according to your
needs.
Solutions:
import tkinter as tk
from tkinter import Canvas, Radiobutton, StringVar
def display_shape():
# Clear the canvas
canvas.delete("all")
selected_shape = shape_var.get()
if selected_shape == "Square":
canvas.create_rectangle(50, 50, 150, 150, fill="blue")
elif selected_shape == "Rectangle":
canvas.create_rectangle(50, 50, 200, 150, fill="green")
elif selected_shape == "Circle":
canvas.create_oval(50, 50, 150, 150, fill="red")
elif selected_shape == "Triangle":
canvas.create_polygon(100, 50, 50, 150, 150, 150,
fill="orange")
elif selected_shape == "Diamond":
canvas.create_polygon(100, 50, 50, 100, 100, 150, 150, 100,
fill="purple")
elif selected_shape == "Pentagon":
canvas.create_polygon(100, 50, 150, 100, 125, 150, 75, 150,
50, 100, fill="pink", outline="red")
After entering the url of website and clicking on the ‘Open webpage’
button, following webbrowser is displayed in separate window.
Word Sorter Program
Project #19
Design Python GUI using Tkinter that sorts words in a
sentence in decreasing order of their length and
displays the sorted words along with their lengths
Introduction:
Welcome to our Word Sorter program! This Python GUI application,
built using Tkinter, helps you sort words in a sentence based on their
length. Simply enter any sentence into the provided entry field, and
our program will sort the words in decreasing order of their length.
Once you've entered the sentence and clicked the "Sort Words"
button, the program will display the sorted words along with their
respective lengths in the text box below.
Lets talk about Frame widget and see how to use it in our code
Frame widget
In Tkinter, a frame is like a box that holds other things, such as
buttons or text boxes. It helps keep everything organized and neat in
your window. You can think of it as a container that groups similar
items together.
Frames are useful because they let you arrange your widgets, like
buttons or labels, in a structured way. They make it easier to manage
and organize different parts of your application. Frames can also
have their own look and style, like a background color or border, to
make your application more visually appealing.
In Tkinter, frames have several properties that you can customize to
control their appearance and behavior.
Here are some common frame properties:
Background (bg): Sets the background color of the frame.
Borderwidth (bd): Sets the width of the border around the frame.
Relief: Determines the appearance of the border. It can be set to
"flat", "raised", "sunken", "groove", or "ridge".
Width (width): Sets the width of the frame.
Height (height): Sets the height of the frame.
Padding (padx, pady): Adds padding around the inside edges of
the frame.
Cursor: Sets the mouse cursor appearance when it is over the
frame.
Highlightbackground: Sets the color of the focus highlight when
the frame does not have focus.
Highlightcolor: Sets the color of the focus highlight when the frame
has focus.
Highlightthickness: Sets the width of the focus highlight.
Solutions:
import tkinter as tk
def sort_and_display():
sentence = entry.get()
words = sentence.split()
# Sort words by length in decreasing order
sorted_words = sorted(words, key=lambda x: len(x),
reverse=True)
# Display sorted words and their lengths
result_text.delete(1.0, tk.END) # Clear previous result
for word in sorted_words:
result_text.insert(tk.END, f"{word} - {len(word)}\n")
# Create the main window
root = tk.Tk()
root.title("Word Sorter")
# Define a bold font style and font name for color_label
bold_font = ("Arial", 12, "bold")
# Create a label to provide instructions
title_label = tk.Label(root, text="Word Sorter Application",bg =
'white',font = bold_font)
title_label.pack(pady=40)
# Create a frame to contain color buttons
label_frame = tk.Frame(root, padx=10, pady=10)
label_frame.pack()
# Create a Lable to provide instructions
label = tk.Label(label_frame, text="Enter any sentence:")
label.pack(side= 'left',pady=10)
# Entry widget for entering a sentence
entry = tk.Entry(label_frame, width=50)
entry.pack(pady=10)
# Button to trigger sorting and displaying
sort_button = tk.Button(root, text="Sort Words",
command=sort_and_display)
sort_button.pack( pady=5)
# Text widget to display the result
result_text = tk.Text(root, width=50, height=10)
result_text.pack(side='bottom',pady=10,padx=10)
# Start the Tkinter event loop
root.mainloop()
Output:
After executing the provided code, a graphical user interface (GUI)
window will appear on your screen. This window features an input
field where you can enter any sentence, a 'Sort words' button to
trigger the word sorting based on their lengths, and a text box below
where the sorted words along with their respective lengths will be
displayed.
Bank Account Simulator
Project #20
Design Python GUI using Tkinter to simulate a bank
account with support for depositing money, withdrawing
money, and checking the balance.
Introduction:
Welcome to our Bank Account Simulator! This easy-to-use Python
GUI application, powered by Tkinter, puts you in control of your
virtual bank account. With just a few clicks, you can deposit money,
withdraw money, and check your remaining balance. Our Bank
Account Simulator features three simple buttons: "Deposit",
"Withdraw", and "Show Balance". When you deposit or withdraw
money, the application instantly updates the label to show your
remaining balance. It's like having your own personal bank right on
your computer screen! Lets get started.
Solutions:
import tkinter as tk
from tkinter import messagebox
# Initial balance
balance = 500
def deposit():
global balance
try:
amount = float(amount_entry.get())
if amount > 0:
balance += amount
update_balance_label()
else:
messagebox.showerror("Error", "Please enter a
valid positive amount.")
except ValueError:
messagebox.showerror("Error", "Please enter a valid numeric
amount.")
def withdraw():
global balance
try:
amount = float(amount_entry.get())
if amount > 0 and amount <= balance:
balance -= amount
update_balance_label()
elif amount <= 0:
messagebox.showerror("Error", "Please enter a valid
positive amount.")
else:
messagebox.showerror("Error", "Insufficient funds.")
except ValueError:
messagebox.showerror("Error", "Please enter a valid numeric
amount.")
def show_balance():
messagebox.showinfo("Balance", f"Your balance is: ${balance}")
def update_balance_label():
balance_label.config(text=f"Balance: ${balance}")
# Create the main window
root = tk.Tk()
root.title("Bank Account Simulator")
# Define bold font for title label
font_bold = ("Times New Roman",25,"bold")
# Create title Label
title_label = tk.Label(root, text ="World Bank", font = font_bold)
title_label.pack()
# Label to display balance
balance_label = tk.Label(root, text=f" Your Remaining Balance:
${balance}")
balance_label.pack(pady=10)
# Create a frame to contain label and entry widget
label_frame = tk.Frame(root, padx=10, pady=10)
label_frame.pack()
# Label to provide instruction
label = tk.Label(label_frame, text= "Enter amount to deposit or
withdraw :")
label.pack(side= 'left')
# Entry widget for amount
amount_entry = tk.Entry(label_frame, width=20)
amount_entry.pack(pady=5)
# Buttons for deposit, withdraw, and show balance
deposit_button = tk.Button(root, text="Deposit", command=deposit)
deposit_button.pack(side=tk.LEFT, padx=5)
withdraw_button = tk.Button(root, text="Withdraw",
command=withdraw)
withdraw_button.pack(side=tk.LEFT, padx=5)
balance_button = tk.Button(root, text="Show Balance",
command=show_balance)
balance_button.pack(side=tk.LEFT, padx=5)
# Start the Tkinter event loop
root.mainloop()
Output:
Upon executing the above code, GUI for bank simulator will be
displayed on your screen. This window comprise the label which is
positioned at the top of the window, indicating the current balance.
This label dynamically updates to reflect changes in the account
balance resulting from deposit or withdrawal transactions. Below the
label, there's an input field where users can enter the amount they
wish to deposit or withdraw.
Buttons:
Deposit Button: Beneath the input field, there's a 'Deposit' button.
Users can click this button to deposit the entered amount into their
account.
Withdraw Button: Following the deposit button, there's a 'Withdraw'
button. Clicking this button allows users to withdraw the entered
amount from their account.
Show Balance Button: Positioned next to the withdraw button,
there's a 'Show Balance' button. Clicking this button triggers a
messagebox displaying the current balance of the account.
qrcode module
The qrcode module in Python is a popular library used for generating
QR codes. QR codes, short for Quick Response codes, are two-
dimensional barcodes that can store various types of information,
such as text, URLs, contact information, or other data.
We will use qrcode module methods to generate qr code for our
program. Lets see what are they
1. qrcode.QRCode(version, error_correction, box_size, border,
data_mask):
This is the core function used to create a QR code object.
version: Controls the size of the code (1 being the smallest, 40 the
largest).
error_correction: Specifies the level of error tolerance (L, M, Q, H).
box_size: Defines the size of each module (pixel size) in the code.
border: Adds a white border around the code (default is 4 modules).
data_mask: Applies a bit mask for further error correction (optional).
2. add_data(data):
This method adds the data you want to encode in the QR code. It
supports various data types like text, URLs, and binary data.
3. make(fit=True):
This method generates the QR code image based on the provided
data and settings.
Fit: If True, ensures the entire data fits even if a smaller version
could be used (default is True).
make_image(fill_color, back_color):
This method converts the QR code data into an image object.
Fill_color: Defines the color of the data modules (default is black).
Back_color: Defines the background color of the image (default is
white).
4.clear():
This method removes all previously added data from the QR code
object.
Solutions:
#Book QR code generator using Python Tkinter
import tkinter as tk
from tkinter import messagebox
import qrcode
def generate_qr_code():
# Get book information
title = book_title_entry.get()
author = author_entry.get()
isbn = isbn_entry.get()
# Combine book information into a single string
book_info = f" Book Title: {title}\nAuthor: {author}\nISBN: {isbn}"
# Generate QR code
qr = qrcode.QRCode(version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10, border=4)
qr.add_data(book_info)
qr.make(fit=True)
# Display QR code
qr_img = qr.make_image(fill_color="black", back_color="white")
qr_img.show()
# Create tkinter window
root = tk.Tk()
root.title("Book QR Code Generator")
# Create title label for form
title_label = tk.Label(root, text="Book QR Code Generator", font=
("Helvetica", 20, "bold"), bg="Yellow", fg="Navy blue")
title_label.grid(row=0, column=0, columnspan=2, padx=5, pady=5 )
# Create labels and entry fields for book information
book_title_label = tk.Label(root, text="Book Title:", font=20)
book_title_label.grid(row=1, column=0, padx=5, pady=5)
book_title_entry = tk.Entry(root)
book_title_entry.grid(row=1, column=1, padx=5, pady=5)
author_label = tk.Label(root, text="Author:", font=20)
author_label.grid(row=2, column=0, padx=5, pady=5)
author_entry = tk.Entry(root)
author_entry.grid(row=2, column=1, padx=5, pady=5)
isbn_label = tk.Label(root, text="ISBN:", font=20)
isbn_label.grid(row=3, column=0, padx=5, pady=5)
isbn_entry = tk.Entry(root)
isbn_entry.grid(row=3, column=1, padx=5, pady=5)
# Create generate button
generate_button = tk.Button(root, text="Generate QR Code", font=
("Arial",18,"bold"), command=generate_qr_code)
generate_button.grid(row=4, column=0, columnspan=2, padx=5,
pady=5)
# Run the tkinter event loop
root.mainloop()
Output:
After executing the provided code, a graphical user interface (GUI)
window will appear on your screen. This GUI window serves as the
interface for the Book QR Code Generator application. Here's what
you can expect to see:
Input Fields:
At the top of the window, there are input fields where users can enter
the book title, author name, and ISBN number.
Generate QR Code Button:
Below the input fields, there's a button labeled 'Generate QR Code'.
Clicking this button initiates the process of generating a QR code for
the entered book information. Users can scan this QR code to
access information about the book using a QR code reader.
Solution:
import tkinter as tk
from tkinter import messagebox
# import EAN13 from barcode module
from barcode import EAN13
# import ImageWriter to generate an image file
from barcode.writer import ImageWriter
def generate_barcode():
# Get ISBN number from user
isbn = entry.get()
# Check length of ISBN
if len(isbn) != 13:
messagebox.showerror("Error", "ISBN must be 13 digits
long!")
return
try:
# Now, let's create an object of EAN13 class and
# pass the number with the ImageWriter() as the writer
ean = EAN13(isbn, writer=ImageWriter())
# Our barcode is ready. Let's save it.
barcode = ean.save('barcoder')
messagebox.showinfo("Success", f"Barcode generated
successfully! Saved as {barcode}")
except Exception as e:
messagebox.showerror("Error", str(e))
# Create tkinter window
root = tk.Tk()
root.title("Book Barcode Generator")
# Create title label for form
title_label = tk.Label(root, text="Book Barcode Generator", font=
("Arial",20,"bold"), bg="black", fg="white")
title_label.pack()
# Create labels and entry fields for book ISBN
label = tk.Label(root, text="Enter ISBN", font=("Arial", 12))
label.pack()
entry = tk.Entry(root)
entry.pack(pady=5)
# Create generate button
generate_button = tk.Button(root, text="Generate Barcode", font=
("Arial", 12),command=generate_barcode)
generate_button.pack()
# Run the tkinter event loop
root.mainloop()
Output:
After executing the provided code, a graphical user interface (GUI)
window will appear on your screen. This GUI window serves as the
interface for the Book Barcode Generator application. Here's what
you can expect to see:
Input Field:
At the top of the window, there's an input field where users can enter
the ISBN number of the book.
Generate Barcode Button:
Below the input field, there's a button labeled 'Generate Barcode'.
Clicking this button initiates the process of generating a barcode for
the entered ISBN number. The generated barcode for the book's
ISBN number will be displayed in separate window on the click of
button. Users can scan this barcode to access information about the
book using a barcode scanner.
Here is the generated barcode for book:
Currency converter
Project #25
Design Pythn GUI application for Currency Convertor
using tkinter
Introduction:
Welcome to the Currency Converter! This program simplifies the
task of converting currency amounts from one currency to another.
With the Currency Converter, you can easily enter the amount you
want to convert, select the source currency, choose the target
currency from the dropdown menu, and with a simple click of the
"Convert" button, the program will fetch the latest exchange rate
from an API and display the converted amount. Using the request
module, our converter always gets the newest exchange rates. This
means you can trust the converted amount to be accurate. The
program has an easy layout, so you can use it without any trouble.
Once you convert, you'll see the result in a popup message.
To fetch newest currency rate, we need to install requests library. We
can install this via pip
pip install requests
With the requests library, you can easily interact with web servers
and retrieve data from web APIs to perform tasks such as web
scraping, data retrieval, or API integration in your Python projects.
Solution:
import tkinter as tk
from tkinter import*
from tkinter import ttk
from tkinter import messagebox
import requests
def convert_currency():
try:
# Get the amount to convert and the selected currencies
amount = float(amount_entry.get())
from_currency = from_currency_combobox.get()
to_currency = to_currency_combobox.get()
# Make a request to the API to get the exchange rate
url = f"https://api.exchangerate-
api.com/v4/latest/{from_currency}"
response = requests.get(url)
data = response.json()
# Convert the amount to the target currency
exchange_rate = data['rates'][to_currency]
converted_amount = amount * exchange_rate
# Display the converted amount
messagebox.showinfo("Conversion Result", f"{amount}
{from_currency} is equal to {converted_amount:.2f} {to_currency}")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
# Function for clearing the Entry field
def clear_all():
amount_entry.delete(0, END)
# Create the main window
root = tk.Tk()
root.title("Currency Converter")
# Create label for title to display
title_label = tk.Label(root, text="Currency Convertor", font=
("Helvetica", 20,"bold"), bg="black", fg="white")
title_label.grid(row=0, column=0, columnspan=2, padx=5, pady=5)
# Label and Entry for the amount to convert
amount_label = ttk.Label(root, text="Amount:", font=8)
amount_label.grid(row=1, column=0, padx=5, pady=5, sticky="w")
amount_entry = ttk.Entry(root)
amount_entry.grid(row=1, column=1, padx=5, pady=5, sticky="ew")
# Label and Combobox for the currency to convert from
from_currency_label = ttk.Label(root, text="From Currency:", font=8)
from_currency_label.grid(row=2, column=0, padx=5, pady=5,
sticky="w")
from_currency_combobox = ttk.Combobox(root, values=["USD",
"EUR", "GBP", "JPY", "INR", "CAD", "CNY", "DKK"], width=10)
from_currency_combobox.grid(row=2, column=1, padx=5, pady=5,
sticky="ew")
from_currency_combobox.current(0)
# Label and Combobox for the currency to convert to
to_currency_label = ttk.Label(root, text="To Currency:", font=8)
to_currency_label.grid(row=3, column=0, padx=5, pady=5,
sticky="w")
to_currency_combobox = ttk.Combobox(root, values=["USD",
"EUR", "GBP", "JPY", "INR", "CAD", "CNY", "DKK"], width=10)
to_currency_combobox.grid(row=3, column=1, padx=5, pady=5,
sticky="ew")
to_currency_combobox.current(1)
# Button to trigger the conversion
convert_button = ttk.Button(root, text="Convert", width=20,
command=convert_currency)
convert_button.grid(row=4, column=0, padx=5, pady=5)
# Function for clearing the Entry field
clear_button = ttk.Button(root, text="Clear", width=20,
command=clear_all)
clear_button.grid(row=4, column=1, padx=5,pady=5)
# Run the Tkinter event loop
root.mainloop()
Output:
Upon executing the above program, you will see a GUI for Currency
Converter. Here what will you see in GUI :
Amount Entry Field: A text entry field where users can input the
amount they wish to convert.
From Currency Dropdown: A dropdown widget allowing users to
select the source currency from a list of available options.
To Currency Dropdown: Another dropdown widget enabling users
to select the target currency to which the amount will be converted.
Convert Button: A button that, when clicked, triggers the conversion
process, displaying the converted amount based on the provided
input.
Clear Button: A button that, when clicked, resets all input fields,
allowing users to start over or make adjustments to their selections.
root = tk.Tk()
root.title("Stopwatch")
date_label = tk.Label(root, text="", font=("Helvetica", 30, "bold"),
fg="white", bg="blue")
date_label.pack()
display_date()
is_running = False
elapsed_time = 0
button_frame = tk.Frame(root)
time_label = tk.Label(button_frame, text="00:00:00", font=
("Helvetica", 48))
time_label.pack()
start_button = tk.Button(button_frame, text="Start", width=10,
command=start_stop, font=30)
start_button.pack(side=tk.LEFT)
stop_button = tk.Button(button_frame, text="Stop", width=10,
command=stop, font=30)
stop_button.pack(side=tk.LEFT)
reset_button = tk.Button(button_frame, text="Reset", width=10,
command=reset, font=30)
reset_button.pack(side=tk.LEFT)
button_frame.pack(anchor="center", pady=5)
root.mainloop()
Output :
After running the provided code, you'll see a graphical user interface
(GUI) window displayed on your screen. Here what will you see in
GUI:
At the top of the window, there will be a title that reads "Stopwatch".
This title indicates the purpose of the application. You will see
current date which will update after 24 hours and three buttons:
stat,stop and reset on application window.
Initially, the stopwatch is in its default state.
After clicking the “Start button”, stopwatch is started as above.
After selecting the 'reset' button, the stopwatch is reset to its initial
state, as shown above.
Drag and Drop Application
Project #32
Design and implement a Python Tkinter application that
allows users to drag and drop objects within a canvas.
Introduction:
Welcome to the Drag and Drop Canvas App! This easy-to-use tool
lets you move things around on a canvas by clicking and dragging
them. Whether you're doodling, designing, or just playing around,
our app makes it simple to move objects where you want them.
With the Drag and Drop Canvas App, you can click on an object,
drag it around the canvas, and drop it where you like. It's like moving
things around on a piece of paper, but on your computer screen!
Solution:
import tkinter as tk
# Function to handle the start of dragging
def on_drag_start(event):
global drag_data
# Find the closest item to the mouse click position
drag_data["item"] = canvas.find_closest(event.x, event.y)[0]
# Record the initial mouse position
drag_data["x"] = event.x
drag_data["y"] = event.y
# Function to handle dragging motion
def on_drag_motion(event):
global drag_data
# Calculate the movement offset
delta_x = event.x - drag_data["x"]
delta_y = event.y - drag_data["y"]
# Move the dragged item by the offset
canvas.move(drag_data["item"], delta_x, delta_y)
# Update the initial mouse position
drag_data["x"] = event.x
drag_data["y"] = event.y
# Function to handle the end of dragging
def on_drag_end(event):
# Reset the dragged item
drag_data["item"] = None
# Create the Tkinter window
root = tk.Tk()
root.title("Drag and Drop Example")
# Create a Label for title
title_label = tk.Label(root, text="Drag and Drop Application", font=
("Helvetica",35,"bold"), bg= "yellow")
title_label.pack()
# Create a canvas widget
canvas = tk.Canvas(root, width=400, height=400, bg="white")
canvas.pack()
# Create a rectangle object to drag
rect = canvas.create_rectangle(50, 50, 150, 150, fill="blue",
tags="draggable")
# Bind events to the draggable rectangle
canvas.tag_bind("draggable", "<Button-1>", on_drag_start)
canvas.tag_bind("draggable", "<B1-Motion>", on_drag_motion)
canvas.tag_bind("draggable", "<ButtonRelease-1>", on_drag_end)
# Create a box where the rectangle can be dropped
box = canvas.create_rectangle(200, 200, 300, 300, outline="black")
# Initialize drag data
drag_data = {"x": 0, "y": 0, "item": None}
# Start the Tkinter event loop
root.mainloop()
Output :
After running the provided code, you'll see a graphical user interface
(GUI) window displayed on your screen.
The application window displays a rectangle object. You can drag
this rectangle and place it inside another rectangle.
After dragging and placing the blue rectangle onto the white
rectangle, the application will appear as shown above.
Traffic Signal Simulator
Project #33
Design and implement a Python Tkinter application for
traffic signal simulator
Introduction:
Welcome to the Traffic Signal Simulator! This simple application
recreates the experience of a traffic signal using a canvas. With just
a click of a button, you can start the simulation and watch as the
traffic lights change colors. The simulator consists of three ovals
representing the traffic lights: red, green, and orange. Initially, all
lights are turned off. When you click the "Start" button, the simulation
begins, and the lights start to turn on and off in a specific sequence.
As the simulation runs, you'll see the traffic lights transition from red
to green to orange, mimicking the typical traffic signal pattern. This
provides a visual representation of how traffic signals work and helps
users understand the sequence of colors used in real-life traffic
lights.
Solution
import tkinter as tk
def setup_traffic_signal(canvas):
# Red light
red_light = canvas.create_oval(25, 50, 75, 100, fill="gray",
outline="gray")
# Yellow light
yellow_light = canvas.create_oval(25, 125, 75, 175, fill="gray",
outline="gray")
# Green light
green_light = canvas.create_oval(25, 200, 75, 250, fill="gray",
outline="gray")
return red_light, yellow_light, green_light
def start_simulation(canvas, lights):
# Define the function to transition to the next state
def next_state():
change_light(canvas, lights, "red")
canvas.after(2000, lambda: change_light(canvas, lights,
"yellow"))
canvas.after(3000, lambda: change_light(canvas, lights,
"green"))
canvas.after(5000, reset_lights)
# Define the function to reset the lights and restart the simulation
def reset_lights():
change_light(canvas, lights, "red")
canvas.after(2000, lambda: change_light(canvas, lights,
"yellow"))
canvas.after(3000, lambda: change_light(canvas, lights,
"green"))
canvas.after(5000, next_state)
# Start the simulation by transitioning to the first state
next_state()
def change_light(canvas, lights, color):
# Turn off all lights
for light in lights.values():
canvas.itemconfig(light, fill="gray")
# Turn on the specified light
canvas.itemconfig(lights[color], fill=color)
def main():
# Create the main Tkinter window
root = tk.Tk()
root.title("Traffic Signal Simulator")
# Create the canvas to display the traffic signal lights
canvas = tk.Canvas(root, width=100, height=300, bg="white")
canvas.pack()
# Set up the traffic signal lights on the canvas
lights = {"red": None, "yellow": None, "green": None}
lights["red"], lights["yellow"], lights["green"] =
setup_traffic_signal(canvas)
# Create the "Start" button to initiate the simulation
start_button = tk.Button(root, text="Start", command=lambda:
start_simulation(canvas, lights))
start_button.pack(pady=10)
# Start the Tkinter event loop
root.mainloop()
# Check if the script is executed directly
if __name__ == "__main__":
main()
Output :
After running above code, following GUI is displayed on your screen.
After clicking the 'start' button, the traffic signal light transitions occur
as depicted above.
Secure Password Validator
Project #34
Design and implement a Python Tkinter GUI for secure
password validator for your account
Introduction:
Welcome to the Secure Password Validator! This handy tool helps
you create strong and secure passwords for your accounts. With
cyber threats on the rise, it's more important to protect your personal
information online. The Secure Password Validator ensures that your
passwords meet the necessary criteria to withstand hacking attempts
and keep your accounts safe. The Password Validator program
checks the validity of a password based on the following criteria:
Length: Password length should be between 6 and 12 characters.
Characters: Password must contain at least one lowercase letter (a-
z), one uppercase letter (A-Z), one digit (0-9), and one special
character from the set [$, #, @].
Confirmation: The program also allows you to confirm your password
to ensure accuracy during input.
To get started, simply enter your desired password in the designated
field and click the "Validate Password" button. If your password
meets the specified criteria, you will receive a confirmation message.
Otherwise, the program will provide feedback on what changes are
needed to make your password compliant.
Solution:
import tkinter as tk
from tkinter import messagebox
# Define global variables
confirm_password_entry = None
def check_password_validity(password):
error_messages = []
if len(password) < 6 or len(password) > 12:
error_messages.append("Password length should be between
6 and 12 characters")
if not any(char.isdigit() for char in password):
error_messages.append("Password should contain at least 1
digit (0-9)")
if not any(char.islower() for char in password):
error_messages.append("Password should contain at least 1
lowercase letter (a-z)")
if not any(char.isupper() for char in password):
error_messages.append("Password should contain at least 1
uppercase letter (A-Z)")
if not any(char in ['$','#','@'] for char in password):
error_messages.append("Password should contain at least 1
of the following characters: $, #, @")
return error_messages
def validate_password():
global confirm_password_entry
# Get password from user
password = password_entry.get()
# Call check_password_validity function
error_messages = check_password_validity(password)
if error_messages:
# Display error messages in red color
error_label.config(text="\n".join(error_messages), fg="red")
else:
# Clear error messages if password is valid
error_label.config(text="")
# Proceed with confirming the password
confirm_password_label = tk.Label(root, text="Confirm
Password:",font=("Arial",13,"bold"), bg="white")
confirm_password_label.grid(row=6, column=0)
confirm_password_entry = tk.Entry(root, show="*")
confirm_password_entry.grid(row=6, column=1)
button_validate.config(state="disabled")
validate_confirm_button = tk.Button(root, text="Validate
Confirm Password",width=25, height=1, bg="blue", fg="white",
font=("Arial", 15,
"bold"),command=validate_confirm_password)
validate_confirm_button.grid(row=8, column=0,columnspan=3,
padx=5, pady=5)
def validate_confirm_password():
global confirm_password_entry
# Get confirm password from user
confirm_password = confirm_password_entry.get()
password = password_entry.get()
if password != confirm_password:
error_label.config(text="Passwords do not match", fg="red")
else:
error_label.config(text="Passwords match", fg="green")
def open_login_form():
global login_window
login_window = tk.Toplevel()
login_window.title("Yahoo Login Form")
italic_font = ("Helvetica", 30, "italic")
title_label = tk.Label(login_window, text="Yahoo!", fg="purple",
font=italic_font)
title_label.grid(row=1, columnspan=2, padx=5, pady=5)
header_label = tk.Label(login_window, text="Sign in to Yahoo
Mail", font=("Arial", 15, "bold"))
header_label.grid(row=2, columnspan=2, padx=5, pady=5)
subheader_label = tk.Label(login_window, text="Sign in using
your Yahoo account", font=("Arial", 12))
subheader_label.grid(row=3, columnspan=2, padx=5, pady=5)
info_frame = tk.Frame(login_window, bg="white", bd=5,
relief="ridge", width=200, height=100, padx=10, pady=10)
info_frame.grid(padx=5, pady=5)
font_bold = ("Arial",10,"bold")
full_name_label = tk.Label(info_frame, text="Username, email or
mobile:", font=font_bold, fg="black", bg="white")
full_name_label.grid(row=2, column=0)
full_name_entry = tk.Entry(info_frame)
full_name_entry.grid(row=2, column=1, columnspan=3)
full_name_entry.config(width=45)
button_signup = tk.Button(login_window, text="Next", bg="blue",
fg="white", font=("Arial", 15, "bold"),
relief=tk.RAISED, bd=3, width=15, height=1,
command=sign_in, cursor="hand2")
button_signup.grid(padx=5,pady=5)
label = tk.Label(login_window, text="Don't have an account ?",
font=("Arial", 10, "bold"))
label.grid(padx=5,pady=5)
button_login = tk.Button(login_window, text="Create an account",
bg="blue", fg="white", font=("Arial", 15, "bold"),
relief=tk.RAISED, bd=3, width=15, height=1,
command=open_signup_form, cursor="hand2")
button_login.grid(padx=5,pady=5)
# Main window
root = tk.Tk()
root.title("Yahoo Login")
italic_font = ("Helvetica", 30, "italic")
title_label = tk.Label(root, text="Yahoo!", fg="purple", font=italic_font)
title_label.grid(row=1, columnspan=3, padx=5, pady=5)
header_label = tk.Label(root, text="Sign in to Yahoo Mail", font=
("Arial", 15, "bold"))
header_label.grid(row=2, columnspan=3, padx=5, pady=5)
subheader_label = tk.Label(root, text="Sign in using your Yahoo
account", font=("Arial", 12))
subheader_label.grid(row=3, columnspan=3, padx=5, pady=5)
font_bold = ("Arial", 10, "bold")
username_label = tk.Label(root, text="Username, email, or mobile:",
font=font_bold, fg="black")
username_label.grid(row=4, column=0, columnspan=3)
username_entry = tk.Entry(root)
username_entry.grid(row=5, column=0, columnspan=3)
username_entry.config(width=45)
button_login = tk.Button(root, text="Next", bg="blue", fg="white",
font=("Arial", 15, "bold"),
relief=tk.RAISED, bd=3, width=15, height=1,
command=sign_in, cursor="hand2")
button_login.grid(row=6, column=0, columnspan=3, padx=5,
pady=5)
label = tk.Label(root, text="Don't have an account?", font=("Arial",
10, "bold"))
label.grid(row=7, column=0, columnspan=3, padx=5, pady=5)
button_signup = tk.Button(root, text="Create an account", bg="blue",
fg="white", font=("Arial", 15, "bold"),
relief=tk.RAISED, bd=3, width=15, height=1,
command=open_signup_form, cursor="hand2")
button_signup.grid(row=8, column=0, columnspan=3, padx=5,
pady=5)
root.mainloop()
Output:
Upon running the provided code for the Email Login System with
Dynamic Account Creation, you'll encounter a Graphical User
Interface (GUI) window designed to facilitate user authentication and
account creation. Here's what you can expect to see:
Main Window:
The main window includes input fields where users can enter their
username, email, or mobile number for authentication.
If the user is already registered, a "Next" button is provided, allowing
them to proceed with the login process.
If the user is not registered, a "Create an Account" button is
provided.
Login Process:
If the user is registered and clicks the "Next" button, the system
verifies their credentials and grants access to their account.
If the user is not registered and clicks the "Create an Account"
button, a message box pops up, informing them that their email is
not registered and prompting them to create an account.
Account Creation Window:
Upon clicking the "Create an Account" button, another window
opens, displaying a form where users can enter their full name, new
Yahoo email, password, and date of birth.
A "Continue" button is provided to submit the form and proceed with
account creation.
Successful Registration:
After clicking the "Continue" button, a message pops up, confirming
that the user has been registered successfully.
Sign In Process:
In the account creation form, a "Sign In" button is available.
When the user enters their new email and clicks the "Sign In" button,
a message appears, indicating that they have successfully signed in.
Main window of Email Login system