1.
Write a Python GUI program to import Tkinter package and create a window
and set its title.
Sample Solution:
Python Code:
import tkinter as tk
# Create instance
parent = tk.Tk()
# Add a title
parent.title("-Welcome to Python tkinter Basic exercises-")
# Start GUI
parent.mainloop()
Sample Output:
2. Write a Python GUI program to import Tkinter package and create a window.
Set its title and add a label to the window.
Sample Solution:
Python Code:
import tkinter as tk
parent = tk.Tk()
parent.title("-Welcome to Python tkinter Basic exercises-")
my_label = tk.Label(parent, text="Label widget")
my_label.grid(column=0, row=0)
parent.mainloop()
Copy
Sample Output:
3. Write a Python GUI program to create a label and change the label font style
(font name, bold, size) using tkinter module.
Sample Solution:
Python Code:
import tkinter as tk
parent = tk.Tk()
parent.title("-Welcome to Python tkinter Basic exercises-")
my_label = tk.Label(parent, text="Hello", font=("Arial Bold",
70))
my_label.grid(column=0, row=0)
parent.mainloop()
Sample Output:
4. Write a Python GUI program to create a window and set the default window
size using tkinter module.
Sample Solution:
Python Code:
import tkinter as tk
parent = tk.Tk()
parent.title("-Welcome to Python tkinter Basic exercises-")
parent.geometry('600x300')
parent.mainloop()
Sample Output:
5. Write a Python GUI program to create a window and disable to resize the
window using tkinter module.
Sample Solution:
Python Code:
import tkinter as tk
parent = tk.Tk()
parent.title("-Welcome to Python tkinter Basic exercises-")
# Disable resizing the GUI
parent.resizable(0,0)
parent.mainloop()
Sample Output:
Flowchart:
6. Write a Python GUI program that adds labels and buttons to the Tkinter
window.
Sample Solution:
Python Code:
import tkinter as tk
# Create the main window
parent = tk.Tk()
parent.title("Button Click Event Handling")
# Create a label widget
label = tk.Label(parent, text="Click the button and check the
label text:")
label.pack()
# Function to handle button click event
def on_button_click():
label.config(text="Button Clicked!")
# Create a button widget
button = tk.Button(parent, text="Click Me",
command=on_button_click)
button.pack()
# Start the Tkinter event loop
parent.mainloop()
Sample Output:
Flowchart:
7. Write a Python program that implements event handling for button clicks using
Tkinter.
Sample Solution:
Python Code:
import tkinter as tk
# Create the main window
root = tk.Tk()
root.title("Button Click Event Handling")
# Create a label widget
label = tk.Label(root, text="Click the button and check the
message text:")
label.pack()
# Function to handle button click event
def on_button_click():
label.config(text="Button Clicked!")
# Create a button widget
button = tk.Button(root, text="Click Me",
command=on_button_click)
button.pack()
# Start the Tkinter event loop
root.mainloop()
Sample Output:
Flowchart:
8. Write a Python program that creates a basic menu bar with menu items using
Tkinter.
Sample Solution:
Python Code:
import tkinter as tk
from tkinter import Menu
# Create the main window
parent = tk.Tk()
parent.title("Spyder (Python 3.6)")
# Create a menu bar
menu_bar = Menu(parent)
parent.config(menu=menu_bar)
# Create a File menu
file_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="File", menu=file_menu)
# Add menu items to the File menu
file_menu.add_command(label="New")
file_menu.add_command(label="Open")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=parent.quit)
# Create an Edit menu
edit_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Edit", menu=edit_menu)
# Add menu items to the Edit menu
edit_menu.add_command(label="Cut")
edit_menu.add_command(label="Copy")
edit_menu.add_command(label="Paste")
# Create a Help menu
help_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Help", menu=help_menu)
# Add menu items to the Help menu
help_menu.add_command(label="About Spyder")
# Start the Tkinter event loop
parent.mainloop()
Flowchart:
9. Write a Python program that displays messages in a messagebox using
Tkinter.
Sample Solution:
Python Code:
import tkinter as tk
from tkinter import messagebox
# Create the main window
parent = tk.Tk()
parent.title("Messagebox Example")
# Function to display a message in a messagebox
def show_message():
messagebox.showinfo("Message", "Hello!")
# Create a button to trigger the messagebox
button = tk.Button(parent, text="Show Message",
command=show_message)
button.pack()
# Start the Tkinter event loop
parent.mainloop()
Sample Output:
Flowchart:
10. Write a Python program that customizes the appearance of labels and
buttons (e.g., fonts, colors) using Tkinter.
Sample Solution:
Python Code:
import tkinter as tk
# Create the main window
parent = tk.Tk()
parent.title("Customizing Labels and Buttons")
# Customize label appearance
label = tk.Label(parent, text="Custom Label", font=("Arial",
18), fg="white", bg="red")
label.pack(pady=10)
# Customize button appearance
button = tk.Button(parent, text="Custom Button",
font=("Helvetica", 14), fg="white", bg="blue")
button.pack(pady=10)
# Start the Tkinter event loop
parent.mainloop()
Copy
In the exercise above,
Create a label with the text "Custom Label" and customize its appearance by
setting the font to Arial with a size of 18, the text color (foreground) to 'white',
and the background color to 'red'.
Create a button with the text "Custom Button" and customize its appearance
by setting the font to Helvetica with a size of 14, the text color (foreground) to
'white', and the background color to 'blue'.
Note: Adjust the font family, size, and colors to match your desired appearance.
The fg attribute is used to set the foreground (text) color, and the bg attribute is
used to set the background color.
Sample Output:
Flowchart:
11. Write a Python GUI program that creates a window with a specific
background color using Tkinter.
Sample Solution:
Python Code:
import tkinter as tk
# Create the main window
parent = tk.Tk()
parent.title("Window with Background Color")
# Set the background color of the window
parent.configure(bg="lightpink") # Replace " lightpink" with
your desired color
# Start the Tkinter event loop
parent.mainloop()
Sample Output:
Flowchart:
12. Write a Python GUI program to add an image (e.g., a logo) to a Tkinter
window.
te a Python GUI program to add an image (e.g., a logo) to a Tkinter window.
Sample Solution:
Python Code:
import tkinter as tk
from PIL import Image, ImageTk
# Create the main window
parent = tk.Tk()
parent.title("Image in Tkinter")
# Load and display an image
#(replace 'your_logo.png' with the path to your image file)
image = Image.open('w3r_logo.png')
image = ImageTk.PhotoImage(image)
# Create a label to display the image
image_label = tk.Label(parent, image=image)
image_label.pack()
# Start the Tkinter event loop
parent.mainloop()
Copy
In the exercise above,
Load an image using the PIL library and open it with Image.open().
Create an ImageTk.PhotoImage object from the loaded image.
Create a label widget (tk.Label) and set its image to the ImageTk.PhotoImage
object.
Finally, use pack() to display the label with the image in the "Tkinter" window.
The "Tkinter" window will display the specified image (e.g., your logo) when we
run this program.
Sample Output:
Flowchart:
13. Write a Python program to design a simple calculator application using
Tkinter with buttons for numbers and arithmetic operations.
Sample Solution:
Python Code:
import tkinter as tk
# Function to update the display
def update_display(value):
current_text = display_var.get()
if current_text == "0":
display_var.set(value)
else:
display_var.set(current_text + value)
# Function to clear the display
def clear_display():
display_var.set("0")
# Function to evaluate the expression and display the result
def calculate_result():
try:
result = eval(display_var.get())
display_var.set(result)
except Exception as e:
display_var.set("Error")
# Create the main window
parent = tk.Tk()
parent.title("Calculator")
# Create a variable to store the current display value
display_var = tk.StringVar()
display_var.set("0")
# Create the display label
display_label = tk.Label(parent, textvariable=display_var,
font=("Arial", 24), anchor="e", bg="lightgray", padx=10,
pady=10)
display_label.grid(row=0, column=0, columnspan=4)
# Define the button layout
button_layout = [
("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("/", 1, 3),
("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("*", 2, 3),
("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("-", 3, 3),
("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("+", 4, 3),
# Create and place the buttons
for (text, row, col) in button_layout:
button = tk.Button(parent, text=text, padx=20, pady=20,
font=("Arial", 18),
command=lambda t=text: update_display(t)
if t != "=" else calculate_result())
button.grid(row=row, column=col)
# Create a Clear button
clear_button = tk.Button(parent, text="C", padx=20, pady=20,
font=("Arial", 18), command=clear_display)
clear_button.grid(row=5, column=0, columnspan=3)
# Start the Tkinter event loop
parent.mainloop()
In the exercise above, we create a simple calculator GUI with buttons for numbers (0-9),
arithmetic operations (+, -, *, /), a decimal point, an equals (=) button to calculate the
result, and a clear (C) button to clear the display.
Note: Click the buttons to input numbers and perform arithmetic operations. The result
will be displayed on the top label.
Sample Output:
14. Write a Python program to implement a Tkinter-based digital clock that
displays the current time on a label.
Sample Solution:
Python Code:
import tkinter as tk
import time
# Function to update the label text with the current time
def update_time():
current_time = time.strftime('%H:%M:%S')
clock_label.config(text=current_time)
root.after(1000, update_time) # Update every 1000
milliseconds (1 second)
# Create the main window
root = tk.Tk()
root.title("Digital Clock")
# Create a label to display the time
clock_label = tk.Label(root, text="", font=("Helvetica", 48))
clock_label.pack(padx=20, pady=20)
# Start updating the time
update_time()
# Start the Tkinter event loop
root.mainloop()
Copy
Explanation:
In the exercise above -
Import the tkinter library as tk and the time module.
The "update_time()" function updates the label's text with the current time. We
use time.strftime('%H:%M:%S') to get the current time in the format
"HH:MM:SS." The label's text is updated every 1000 milliseconds (1 second)
using the root.after method.
Create the main window with the title "Digital Clock."
A label (clock_label) is created to display the time. We set the font size to 48
points for a larger display.
Update the time by calling the "update_time()" function.
With root.mainloop(), we start the Tkinter event loop, which keeps the GUI
running and updates the time.
Sample Output:
15. Write a Python program that implements a temperature converter application
using Tkinter, allowing users to convert between Celsius and Fahrenheit.
Python Code:
import tkinter as tk
# Function to convert from Celsius to Fahrenheit
def celsius_to_fahrenheit():
try:
celsius = float(celsius_entry.get())
fahrenheit = (celsius * 9/5) + 32
result_label.config(text=f"{celsius:.2f}°C =
{fahrenheit:.2f}°F")
except ValueError:
result_label.config(text="Invalid input")
# Function to convert from Fahrenheit to Celsius
def fahrenheit_to_celsius():
try:
fahrenheit = float(fahrenheit_entry.get())
celsius = (fahrenheit - 32) * 5/9
result_label.config(text=f"{fahrenheit:.2f}°F =
{celsius:.2f}°C")
except ValueError:
result_label.config(text="Invalid input")
# Create the main window
parent = tk.Tk()
parent.title("Temperature Converter")
# Celsius to Fahrenheit Conversion
celsius_label = tk.Label(parent, text="Input Celsius:")
celsius_label.grid(row=0, column=0)
celsius_entry = tk.Entry(parent)
celsius_entry.grid(row=0, column=1)
c_to_f_button = tk.Button(parent, text="Convert to
Fahrenheit", command=celsius_to_fahrenheit)
c_to_f_button.grid(row=0, column=2)
# Fahrenheit to Celsius Conversion
fahrenheit_label = tk.Label(parent, text="Input Fahrenheit:")
fahrenheit_label.grid(row=1, column=0)
fahrenheit_entry = tk.Entry(parent)
fahrenheit_entry.grid(row=1, column=1)
f_to_c_button = tk.Button(parent, text="Convert to Celsius",
command=fahrenheit_to_celsius)
f_to_c_button.grid(row=1, column=2)
# Display the result
result_label = tk.Label(parent, text="", font=("Helvetica",
14))
result_label.grid(row=2, columnspan=3)
# Start the Tkinter event loop
parent.mainloop()
Explanation:
In the exercise above -
Temperature values can be entered in Celsius or Fahrenheit.
The result label will appear when they click the corresponding conversion
button.
A ValueError exception is thrown when invalid input is received, and the result
label is displayed with the text "Invalid input".
As a result of the Tkinter event loop (root.mainloop()), the GUI is kept running
and responsive to user input.
Sample Output:
16. Write a Python program to create a Tkinter-based login form with input fields
for userid and password.
Python Code:
import tkinter as tk
from tkinter import messagebox
# Function to validate the login
def validate_login():
userid = username_entry.get()
password = password_entry.get()
# You can add your own validation logic here
if userid == "admin" and password == "password":
messagebox.showinfo("Login Successful", "Welcome,
Admin!")
else:
messagebox.showerror("Login Failed", "Invalid username
or password")
# Create the main window
parent = tk.Tk()
parent.title("Login Form")
# Create and place the username label and entry
username_label = tk.Label(parent, text="Userid:")
username_label.pack()
username_entry = tk.Entry(parent)
username_entry.pack()
# Create and place the password label and entry
password_label = tk.Label(parent, text="Password:")
password_label.pack()
password_entry = tk.Entry(parent, show="*") # Show asterisks
for password
password_entry.pack()
# Create and place the login button
login_button = tk.Button(parent, text="Login",
command=validate_login)
login_button.pack()
# Start the Tkinter event loop
parent.mainloop()
Copy
Explanation:
In the exercise above -
First we import the necessary modules from Tkinter.
The "validate_login()" function validates login credentials.
Next we create the main window with the title "Login Form."
Input fields for userid and password are created using tk.Entry widgets. The
show="*" option for the password entry field displays asterisks.
A login button is created using tk.Button, and its command is set to the
validate_login function.
The Tkinter event loop (root.mainloop()) keeps the GUI running and
responsive to user interactions.
Sample Output:
Flowchart:
17. Write a Python GUI program to add tooltips to buttons and labels in a Tkinter
window.
olution:
Python Code:
import tkinter as tk
# Function to show tooltips
def show_tooltip(event, tooltip_text):
tooltip.geometry(f"+{event.x_parent + 10}+{event.y_parent
+ 10}") # Adjust tooltip position
tooltip_label.config(text=tooltip_text)
tooltip.deiconify()
# Function to hide tooltips
def hide_tooltip(event):
tooltip.withdraw()
# Create the main window
parent = tk.Tk()
parent.title("Tooltip Example")
# Create a button with a tooltip
button = tk.Button(parent, text="Button with Tooltip")
button.pack(padx=10, pady=10)
button.bind("<Enter>", lambda event, text="This is a button.":
show_tooltip(event, text))
button.bind("<Leave>", hide_tooltip)
# Create a label with a tooltip
label = tk.Label(parent, text="Label with Tooltip")
label.pack(padx=10, pady=10)
label.bind("<Enter>", lambda event, text="This is a label.":
show_tooltip(event, text))
label.bind("<Leave>", hide_tooltip)
# Create the tooltip window (hidden by default)
tooltip = tk.Toplevel(parent)
tooltip.withdraw()
tooltip_label = tk.Label(tooltip, text="",
background="lightyellow", relief="solid", borderwidth=1)
tooltip_label.pack()
# Start the Tkinter event loop
parent.mainloop()
Explanation:
In the exercise above -
We create a tooltip window (tooltip) using tk.Toplevel and initially hide it using
tooltip.withdraw().
The "show_tooltip()" function is modified to position and display the tooltip
window when the mouse enters the widget. We use tooltip.deiconify() to show
the tooltip.
The "hide_tooltip()" function is used to hide the tooltip when the mouse leaves
the widget by calling tooltip.withdraw().
Sample Output:
18. Write a Python GUI program to create a window that closes when a "Close"
button is clicked.
Sample Solution:
Python Code:
import tkinter as tk
# Function to close the window
def close_window():
parent.destroy()
# Create the main window
parent = tk.Tk()
parent.title("Close Window Example")
# Create a label
label = tk.Label(parent, text="Click the 'Close' button to
close this window.")
label.pack(padx=25, pady=25)
# Create a close button
close_button = tk.Button(parent, text="Close",
command=close_window)
close_button.pack()
# Start the Tkinter event loop
parent.mainloop()
Explanation:
In the exercise above -
First we import the 'tkinter' library and create the main window using tk.Tk().
Next we define a function called "close_window()" that calls root.destroy() to
close the main window.
A label and a "Close" button are added to the window. The button's command
parameter is set to 'close_window', so clicking the button will execute the
"close_window()" function.
The program starts the Tkinter event loop using parent.mainloop(), which
keeps the GUI window running.
Sample Output:
19. Write a Python program that creates a Tkinter application that allows users to
select and display their favorite color using a color picker.
import tkinter as tk
from tkcolorpicker import askcolor
# Function to open the color picker and display the selected
color
def choose_color():
color = askcolor()[1] # askcolor() returns (color,
color_name)
if color:
color_label.config(text=f"Selected Color: {color}",
bg=color)
# Create the main window
parent = tk.Tk()
parent.title("Color Picker")
# Create a label to display the selected color
color_label = tk.Label(parent, text="Selected Color: None",
font=("Helvetica", 14), padx=10, pady=10)
color_label.pack()
# Create a button to open the color picker
choose_button = tk.Button(parent, text="Choose Color",
command=choose_color)
choose_button.pack(pady=10)
# Start the Tkinter event loop
parent.mainloop()
Copy
Explanation:
In the exercise above -
First we import the "tkinter" library and the askcolor function from
"tkcolorpicker".
The "choose_color()" function is defined to open the color picker dialog using
askcolor(), which returns the selected color. We then update the label's text
and background color to display the selected color.
The main window is created using tk.Tk().
A label is created to display the selected color, and a button is created to
open the color picker dialog.
The program starts the Tkinter event loop using root.mainloop().
Sample Output:
Flowchart:
20. Write a Python program that implements a Tkinter-based timer application
that counts down from a specified time when started.
import tkinter as tk
from tkinter import ttk
# Function to start the timer
def start_timer():
global remaining_time
try:
minutes = int(minutes_entry.get())
seconds = int(seconds_entry.get())
remaining_time = minutes * 60 + seconds
update_timer()
start_button.config(state="disabled")
stop_button.config(state="active")
except ValueError:
pass
# Function to update the timer
def update_timer():
global remaining_time
if remaining_time > 0:
minutes = remaining_time // 60
seconds = remaining_time % 60
timer_label.config(text=f"{minutes:02d}:
{seconds:02d}")
remaining_time -= 1
parent.after(1000, update_timer) # Update every 1000
milliseconds (1 second)
else:
timer_label.config(text="00:00")
start_button.config(state="active")
stop_button.config(state="disabled")
# Function to stop the timer
def stop_timer():
global remaining_time
remaining_time = 0
timer_label.config(text="00:00")
start_button.config(state="active")
stop_button.config(state="disabled")
# Create the main window
parent = tk.Tk()
parent.title("Timer Application")
# Create and place input fields for minutes and seconds
minutes_label = tk.Label(parent, text="Minutes:")
minutes_label.grid(row=0, column=0)
minutes_entry = tk.Entry(parent)
minutes_entry.grid(row=0, column=1)
minutes_entry.insert(0, "0")
seconds_label = tk.Label(parent, text="Seconds:")
seconds_label.grid(row=1, column=0)
seconds_entry = tk.Entry(parent)
seconds_entry.grid(row=1, column=1)
seconds_entry.insert(0, "0")
# Create and place timer label
timer_label = tk.Label(parent, text="00:00",
font=("Helvetica", 48))
timer_label.grid(row=2, columnspan=2)
# Create and place start and stop buttons
start_button = ttk.Button(parent, text="Start",
command=start_timer)
start_button.grid(row=3, column=0)
stop_button = ttk.Button(parent, text="Stop",
command=stop_timer, state="disabled")
stop_button.grid(row=3, column=1)
# Initialize the remaining time
remaining_time = 0
# Start the Tkinter event loop
parent.mainloop()
Copy
Explanation:
In the exercise above -
First we create a Tkinter window with input fields for minutes and seconds, a
timer label, and start and stop buttons.
When the user enters the desired time in minutes and seconds and clicks the
"Start" button, the "start_timer()" function is called. It calculates the total
remaining time in seconds and updates the timer using the "update_timer()"
function.
By subtracting one second from the remaining time, "update_timer()" updates
the timer label every second and schedules itself to run again after 1000
milliseconds (1 second). The timer stops when the remaining time reaches
zero, and the "Start" button is reactivated.
The "Stop" button can stop the timer at any time.
Sample Output: