Unit 5 Ques Ans -Python
Unit 5 Ques Ans -Python
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
# 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()
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()
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.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.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
parent = tk.Tk()
label.pack()
def on_button_click():
label.config(text="Button Clicked!")
button.pack()
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
root = tk.Tk()
label.pack()
# Function to handle button click event
def on_button_click():
label.config(text="Button Clicked!")
button.pack()
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
parent = tk.Tk()
menu_bar = Menu(parent)
parent.config(menu=menu_bar)
menu_bar.add_cascade(label="File", menu=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)
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")
menu_bar.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(label="About Spyder")
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
parent = tk.Tk()
parent.title("Messagebox Example")
def show_message():
messagebox.showinfo("Message", "Hello!")
button.pack()
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
parent = tk.Tk()
label.pack(pady=10)
# Customize button appearance
button.pack(pady=10)
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.mainloop()
Sample Output:
Flowchart:
12. Write a Python GUI program to add an image (e.g., a logo) to a Tkinter
window.
Sample Solution:
Python Code:
import tkinter as tk
parent = tk.Tk()
parent.title("Image in Tkinter")
image = Image.open('w3r_logo.png')
image = ImageTk.PhotoImage(image)
image_label.pack()
parent.mainloop()
Copy
In the exercise above,
Load an image using the PIL library and open it with Image.open().
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:
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)
def clear_display():
display_var.set("0")
def calculate_result():
try:
result = eval(display_var.get())
display_var.set(result)
except Exception as e:
display_var.set("Error")
parent = tk.Tk()
parent.title("Calculator")
# Create a variable to store the current display value
display_var = tk.StringVar()
display_var.set("0")
button_layout = [
button.grid(row=row, column=col)
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
def update_time():
current_time = time.strftime('%H:%M:%S')
clock_label.config(text=current_time)
root = tk.Tk()
root.title("Digital Clock")
clock_label.pack(padx=20, pady=20)
update_time()
root.mainloop()
Copy
Explanation:
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.
A label (clock_label) is created to display the time. We set the font size to 48
points for a larger display.
Sample Output:
Python Code:
import tkinter as tk
def celsius_to_fahrenheit():
try:
celsius = float(celsius_entry.get())
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())
result_label.config(text=f"{fahrenheit:.2f}°F =
{celsius:.2f}°C")
except ValueError:
result_label.config(text="Invalid input")
parent = tk.Tk()
parent.title("Temperature Converter")
celsius_label.grid(row=0, column=0)
celsius_entry = tk.Entry(parent)
celsius_entry.grid(row=0, column=1)
c_to_f_button.grid(row=0, column=2)
# Fahrenheit to Celsius Conversion
fahrenheit_label.grid(row=1, column=0)
fahrenheit_entry = tk.Entry(parent)
fahrenheit_entry.grid(row=1, column=1)
f_to_c_button.grid(row=1, column=2)
result_label.grid(row=2, columnspan=3)
parent.mainloop()
Explanation:
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
userid = username_entry.get()
password = password_entry.get()
else:
parent = tk.Tk()
parent.title("Login Form")
username_label.pack()
username_entry = tk.Entry(parent)
username_entry.pack()
password_entry.pack()
login_button.pack()
parent.mainloop()
Copy
Explanation:
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
tooltip_label.config(text=tooltip_text)
tooltip.deiconify()
def hide_tooltip(event):
tooltip.withdraw()
parent = tk.Tk()
parent.title("Tooltip Example")
button.pack(padx=10, pady=10)
button.bind("<Leave>", hide_tooltip)
label.pack(padx=10, pady=10)
label.bind("<Leave>", hide_tooltip)
# Create the tooltip window (hidden by default)
tooltip = tk.Toplevel(parent)
tooltip.withdraw()
tooltip_label.pack()
parent.mainloop()
Explanation:
We create a tooltip window (tooltip) using tk.Toplevel and initially hide it using
tooltip.withdraw().
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
def close_window():
parent.destroy()
# Create a label
label.pack(padx=25, pady=25)
close_button.pack()
parent.mainloop()
Explanation:
First we import the 'tkinter' library and create the main window using tk.Tk().
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
def choose_color():
if color:
parent = tk.Tk()
parent.title("Color Picker")
choose_button.pack(pady=10)
parent.mainloop()
Copy
Explanation:
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.
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
def start_timer():
global remaining_time
try:
minutes = int(minutes_entry.get())
seconds = int(seconds_entry.get())
update_timer()
start_button.config(state="disabled")
stop_button.config(state="active")
except ValueError:
pass
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
else:
timer_label.config(text="00:00")
start_button.config(state="active")
stop_button.config(state="disabled")
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")
parent = tk.Tk()
parent.title("Timer Application")
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.grid(row=1, column=0)
seconds_entry = tk.Entry(parent)
seconds_entry.grid(row=1, column=1)
seconds_entry.insert(0, "0")
timer_label.grid(row=2, columnspan=2)
start_button.grid(row=3, column=0)
stop_button.grid(row=3, column=1)
remaining_time = 0
parent.mainloop()
Copy
Explanation:
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.
Sample Output: