Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Scenario Based Questions in GUI Programming

The document presents various scenario-based questions and solutions for GUI programming in Python using Tkinter. It includes examples such as a login form, calculator, to-do list, temperature converter, and more, each demonstrating specific functionalities and user interactions. Each scenario provides a brief description of the task along with the corresponding Python code to implement the GUI application.

Uploaded by

natuhari91
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Scenario Based Questions in GUI Programming

The document presents various scenario-based questions and solutions for GUI programming in Python using Tkinter. It includes examples such as a login form, calculator, to-do list, temperature converter, and more, each demonstrating specific functionalities and user interactions. Each scenario provides a brief description of the task along with the corresponding Python code to implement the GUI application.

Uploaded by

natuhari91
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Scenario-based questions and solutions in Python for GUI programming using Tkinter.

Scenario 1: Simple Login Form


Question:
Create a GUI application for a login form with fields for username and password. On clicking
the "Login" button, display a message:

 "Login Successful" if the username is "admin" and the password is "1234".


 Otherwise, display "Invalid Credentials".

Solution:

import tkinter as tk
from tkinter import messagebox

def login():
username = entry_username.get()
password = entry_password.get()

if username == "admin" and password == "1234":


messagebox.showinfo("Login Status", "Login Successful")
else:
messagebox.showerror("Login Status", "Invalid Credentials")

# Create window
window = tk.Tk()
window.title("Login Form")
window.geometry("300x200")

# Labels
tk.Label(window, text="Username:").pack(pady=5)
entry_username = tk.Entry(window)
entry_username.pack(pady=5)

tk.Label(window, text="Password:").pack(pady=5)
entry_password = tk.Entry(window, show="*")
entry_password.pack(pady=5)

# Login button
btn_login = tk.Button(window, text="Login", command=login)
btn_login.pack(pady=20)

window.mainloop()

Scenario 2: Basic Calculator


Question:
Create a GUI calculator that supports addition, subtraction, multiplication, and division.
Provide two input fields and display the result using a label.

5acXjz Uk
Solution:

import tkinter as tk
from tkinter import messagebox

def calculate(operation):
try:
num1 = float(entry_num1.get())
num2 = float(entry_num2.get())

if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
if num2 == 0:
raise ValueError("Cannot divide by zero")
result = num1 / num2

lbl_result.config(text=f"Result: {result}")
except ValueError as e:
messagebox.showerror("Error", str(e))

# GUI Setup
window = tk.Tk()
window.title("Simple Calculator")
window.geometry("350x250")

tk.Label(window, text="Number 1:").pack()


entry_num1 = tk.Entry(window)
entry_num1.pack()

tk.Label(window, text="Number 2:").pack()


entry_num2 = tk.Entry(window)
entry_num2.pack()

# Operation Buttons
frame = tk.Frame(window)
frame.pack(pady=10)

for op in ['+', '-', '*', '/']:


tk.Button(frame, text=op, width=8, command=lambda o=op:
calculate(o)).pack(side=tk.LEFT, padx=5)

lbl_result = tk.Label(window, text="Result: ")


lbl_result.pack(pady=20)

window.mainloop()

Scenario 3: To-Do List


Question:
Create a simple To-Do List application where users can add tasks, view tasks, and delete
selected tasks using a Listbox.

5acXjz Uk
Solution:

import tkinter as tk
from tkinter import messagebox

def add_task():
task = entry_task.get()
if task:
listbox_tasks.insert(tk.END, task)
entry_task.delete(0, tk.END)
else:
messagebox.showwarning("Warning", "Task cannot be empty!")

def delete_task():
try:
selected_task = listbox_tasks.curselection()[0]
listbox_tasks.delete(selected_task)
except IndexError:
messagebox.showwarning("Warning", "Please select a task to
delete.")

# GUI Setup
window = tk.Tk()
window.title("To-Do List")
window.geometry("300x400")

entry_task = tk.Entry(window, width=20)


entry_task.pack(pady=10)

btn_add = tk.Button(window, text="Add Task", command=add_task)


btn_add.pack()

listbox_tasks = tk.Listbox(window, width=30, height=10)


listbox_tasks.pack(pady=10)

btn_delete = tk.Button(window, text="Delete Task", command=delete_task)


btn_delete.pack()

window.mainloop()

Scenario 4: Temperature Converter


Question:
Create a temperature converter that converts Celsius to Fahrenheit and vice versa.

Solution:

import tkinter as tk

def convert_temp():
try:
temp = float(entry_temp.get())
if var.get() == 1:
result = (temp * 9/5) + 32
lbl_result.config(text=f"{temp}°C = {result:.2f}°F")
else:
result = (temp - 32) * 5/9

5acXjz Uk
lbl_result.config(text=f"{temp}°F = {result:.2f}°C")
except ValueError:
lbl_result.config(text="Invalid input! Please enter a number.")

# GUI Setup
window = tk.Tk()
window.title("Temperature Converter")
window.geometry("350x200")

tk.Label(window, text="Enter Temperature:").pack(pady=5)


entry_temp = tk.Entry(window)
entry_temp.pack(pady=5)

var = tk.IntVar(value=1)
tk.Radiobutton(window, text="Celsius to Fahrenheit", variable=var,
value=1).pack()
tk.Radiobutton(window, text="Fahrenheit to Celsius", variable=var,
value=2).pack()

btn_convert = tk.Button(window, text="Convert", command=convert_temp)


btn_convert.pack(pady=10)

lbl_result = tk.Label(window, text="Result:")


lbl_result.pack()

window.mainloop()

Scenario 5: Simple Interest Calculator


Question: Create a GUI to calculate the Simple Interest using the formula:

SI=P×R×T100SI = \frac{P \times R \times T}{100}

Where:

 P = Principal amount
 R = Rate of interest
 T = Time in years

Solution:

import tkinter as tk

def calculate_si():
try:
p = float(entry_p.get())
r = float(entry_r.get())
t = float(entry_t.get())
si = (p * r * t) / 100
lbl_result.config(text=f"Simple Interest: ₹{si:.2f}")
except ValueError:
lbl_result.config(text="Invalid Input")

# GUI Setup
window = tk.Tk()
window.title("Simple Interest Calculator")

5acXjz Uk
tk.Label(window, text="Principal (₹)").pack()
entry_p = tk.Entry(window)
entry_p.pack()

tk.Label(window, text="Rate of Interest (%)").pack()


entry_r = tk.Entry(window)
entry_r.pack()

tk.Label(window, text="Time (Years)").pack()


entry_t = tk.Entry(window)
entry_t.pack()

btn_calc = tk.Button(window, text="Calculate", command=calculate_si)


btn_calc.pack(pady=10)

lbl_result = tk.Label(window, text="Simple Interest: ₹0.00")


lbl_result.pack()

window.mainloop()

Scenario 6: Currency Converter


Question: Create a currency converter that converts USD to INR (1 USD = ₹83).

Solution:

import tkinter as tk

def convert_currency():
try:
usd = float(entry_usd.get())
inr = usd * 83
lbl_result.config(text=f"₹{inr:.2f}")
except ValueError:
lbl_result.config(text="Invalid Input")

# GUI Setup
window = tk.Tk()
window.title("Currency Converter")

tk.Label(window, text="Enter USD:").pack()


entry_usd = tk.Entry(window)
entry_usd.pack()

btn_convert = tk.Button(window, text="Convert to INR",


command=convert_currency)
btn_convert.pack(pady=10)

lbl_result = tk.Label(window, text="₹0.00")


lbl_result.pack()

window.mainloop()

Scenario 7: Age Calculator

5acXjz Uk
Question: Create an Age Calculator where users enter their birth year and get their age.

Solution:

import tkinter as tk
from datetime import datetime

def calculate_age():
try:
birth_year = int(entry_year.get())
current_year = datetime.now().year
age = current_year - birth_year
lbl_result.config(text=f"You are {age} years old.")
except ValueError:
lbl_result.config(text="Invalid Year")

# GUI Setup
window = tk.Tk()
window.title("Age Calculator")

tk.Label(window, text="Enter Birth Year:").pack()


entry_year = tk.Entry(window)
entry_year.pack()

btn_calculate = tk.Button(window, text="Calculate Age",


command=calculate_age)
btn_calculate.pack(pady=10)

lbl_result = tk.Label(window, text="Your Age will be shown here.")


lbl_result.pack()

window.mainloop()

Scenario 8: Password Generator


Question: Create a password generator that generates random 8-character passwords.

Solution:

import tkinter as tk
import string
import random

def generate_password():
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(8))
lbl_result.config(text=f"Generated Password: {password}")

# GUI Setup
window = tk.Tk()
window.title("Password Generator")

btn_generate = tk.Button(window, text="Generate Password",


command=generate_password)
btn_generate.pack(pady=10)

lbl_result = tk.Label(window, text="Generated Password: ")

5acXjz Uk
lbl_result.pack()

window.mainloop()

Scenario 9: Countdown Timer


Question: Create a countdown timer that takes seconds as input and counts down to zero.

Solution:

import tkinter as tk
import time

def start_countdown():
try:
count = int(entry_time.get())
while count >= 0:
lbl_result.config(text=f"Time Remaining: {count} seconds")
window.update()
time.sleep(1)
count -= 1
lbl_result.config(text="Time's up!")
except ValueError:
lbl_result.config(text="Invalid Input")

# GUI Setup
window = tk.Tk()
window.title("Countdown Timer")

tk.Label(window, text="Enter Time (Seconds)").pack()


entry_time = tk.Entry(window)
entry_time.pack()

btn_start = tk.Button(window, text="Start Countdown",


command=start_countdown)
btn_start.pack()

lbl_result = tk.Label(window, text="Time Remaining: ")


lbl_result.pack()

window.mainloop()

Scenario 10: Rock Paper Scissors Game


Question: Create a simple Rock Paper Scissors game using buttons.

Solution:

import tkinter as tk
import random

def play(choice):
options = ["Rock", "Paper", "Scissors"]
computer_choice = random.choice(options)

5acXjz Uk
if choice == computer_choice:
result = "It's a tie!"
elif (choice == "Rock" and computer_choice == "Scissors") or \
(choice == "Paper" and computer_choice == "Rock") or \
(choice == "Scissors" and computer_choice == "Paper"):
result = "You Win!"
else:
result = "You Lose!"
lbl_result.config(text=f"Computer: {computer_choice}\n{result}")

# GUI Setup
window = tk.Tk()
window.title("Rock Paper Scissors")

tk.Label(window, text="Choose Rock, Paper, or Scissors").pack()

frame = tk.Frame(window)
frame.pack()

for choice in ["Rock", "Paper", "Scissors"]:


tk.Button(frame, text=choice, command=lambda c=choice:
play(c)).pack(side=tk.LEFT)

lbl_result = tk.Label(window, text="")


lbl_result.pack()

window.mainloop()

Scenario 11: Color Changer


Question: Create a GUI that changes the background color when clicking on a button.

Solution:

import tkinter as tk

def change_color(color):
window.configure(bg=color)

# GUI Setup
window = tk.Tk()
window.title("Color Changer")
window.geometry("300x200")

tk.Button(window, text="Red", command=lambda:


change_color("red")).pack(side=tk.LEFT)
tk.Button(window, text="Green", command=lambda:
change_color("green")).pack(side=tk.LEFT)
tk.Button(window, text="Blue", command=lambda:
change_color("blue")).pack(side=tk.LEFT)

window.mainloop()

Scenario 12: Digital Clock

5acXjz Uk
Question: Create a digital clock using GUI that updates every second.

Solution:

import tkinter as tk
from time import strftime

def update_time():
current_time = strftime('%H:%M:%S %p')
lbl_time.config(text=current_time)
lbl_time.after(1000, update_time)

# GUI Setup
window = tk.Tk()
window.title("Digital Clock")

lbl_time = tk.Label(window, font=('Helvetica', 48), fg='blue')


lbl_time.pack()

update_time()
window.mainloop()

Scenario 13: Stopwatch App


Task: Build a stopwatch with Start, Stop, and Reset buttons.

Solution:

import tkinter as tk

counter = 0
running = False

def update_timer():
if running:
global counter
counter += 1
time_display.config(text=f"{counter//60:02d}:{counter%60:02d}")
root.after(1000, update_timer)

def start_timer():
global running
if not running:
running = True
update_timer()

def stop_timer():
global running
running = False

def reset_timer():
global running, counter
running = False
counter = 0
time_display.config(text="00:00")

root = tk.Tk()

5acXjz Uk
root.title("Stopwatch")

time_display = tk.Label(root, text="00:00", font=("Arial", 30))


time_display.pack(pady=10)

btn_start = tk.Button(root, text="Start", command=start_timer)


btn_stop = tk.Button(root, text="Stop", command=stop_timer)
btn_reset = tk.Button(root, text="Reset", command=reset_timer)

btn_start.pack(side=tk.LEFT, padx=5, pady=5)


btn_stop.pack(side=tk.LEFT, padx=5, pady=5)
btn_reset.pack(side=tk.LEFT, padx=5, pady=5)

root.mainloop()

Scenario 14: Random Password Generator


Task: Design an app that generates secure passwords based on user-defined criteria.

Solution:

import tkinter as tk
import string
import random

def generate_password():
length = int(entry_length.get())
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choices(characters, k=length))
result.set(password)

root = tk.Tk()
root.title("Password Generator")

tk.Label(root, text="Password Length:").pack(pady=5)


entry_length = tk.Entry(root, width=10)
entry_length.pack(pady=5)

btn_generate = tk.Button(root, text="Generate", command=generate_password)


btn_generate.pack(pady=5)

result = tk.StringVar()
tk.Entry(root, textvariable=result, width=30,
state='readonly').pack(pady=5)

root.mainloop()

Scenario 15: Quiz App


Task: Create a quiz app that presents questions and tracks the score.

Solution:

import tkinter as tk

5acXjz Uk
from tkinter import messagebox

questions = [
{"question": "What is the capital of France?", "answer": "Paris"},
{"question": "Which planet is known as the Red Planet?", "answer":
"Mars"},
{"question": "What is 5 + 7?", "answer": "12"}
]

current_question = 0
score = 0

def check_answer():
global current_question, score
user_answer = entry_answer.get().strip()
if user_answer.lower() ==
questions[current_question]["answer"].lower():
score += 1
messagebox.showinfo("Correct!", "That's the right answer!")
else:
messagebox.showerror("Wrong!", f"Correct answer:
{questions[current_question]['answer']}")

current_question += 1
if current_question < len(questions):
lbl_question.config(text=questions[current_question]["question"])
entry_answer.delete(0, tk.END)
else:
messagebox.showinfo("Quiz Over", f"Your final score is
{score}/{len(questions)}")
root.destroy()

root = tk.Tk()
root.title("Quiz App")

lbl_question = tk.Label(root, text=questions[current_question]["question"],


font="Arial 14")
lbl_question.pack(pady=10)

entry_answer = tk.Entry(root)
entry_answer.pack(pady=5)

btn_submit = tk.Button(root, text="Submit", command=check_answer)


btn_submit.pack(pady=5)

root.mainloop()

Scenario 16: Text-to-Speech Converter


Task: Create a simple text-to-speech converter using pyttsx3.

Solution:

import tkinter as tkv


import pyttsx3

5acXjz Uk
engine = pyttsx3.init()

def speak():
text = entry_text.get("1.0", tk.END).strip()
if text:
engine.say(text)
engine.runAndWait()

root = tk.Tk()
root.title("Text to Speech")

entry_text = tk.Text(root, height=5, width=40)


entry_text.pack(padx=10, pady=10)

btn_speak = tk.Button(root, text="Speak", command=speak)


btn_speak.pack(pady=5)

root.mainloop()

Scenario 17: Simple Unit Converter


Task: Design a basic unit converter for converting kilometers to miles.

Solution:

import tkinter as tk

def convert():
km = float(entry_km.get())
miles = km * 0.621371
result.set(f"{miles:.2f} miles")

root = tk.Tk()
root.title("Unit Converter")

tk.Label(root, text="Kilometers:").grid(row=0, column=0, padx=5, pady=5)


entry_km = tk.Entry(root)
entry_km.grid(row=0, column=1, padx=5, pady=5)

btn_convert = tk.Button(root, text="Convert", command=convert)


btn_convert.grid(row=1, column=0, columnspan=2, pady=10)

result = tk.StringVar()
tk.Label(root, textvariable=result, font="Arial 12 bold").grid(row=2,
column=0, columnspan=2)

root.mainloop()

5acXjz Uk
scenario-based questions and solutions focused on Tkinter GUI
widgets

Scenario 1: Button Click Counter


Question:
Create a GUI with a button labeled "Click Me!". Each time the button is clicked, the counter should
increase by 1 and display the updated count.

Solution:

import tkinter as tk

count = 0

def increase_count():
global count
count += 1
label.config(text=f"Count: {count}")

root = tk.Tk()
root.title("Button Click Counter")

label = tk.Label(root, text="Count: 0", font=("Arial", 20))


label.pack(pady=10)

btn = tk.Button(root, text="Click Me!", command=increase_count)


btn.pack(pady=5)

root.mainloop()

Scenario 2: Entry Field Validation


Question:
Design a GUI app with an entry field that only accepts numbers. If a non-numeric value is entered,
display an error message.

Solution:

import tkinter as tk
from tkinter import messagebox

def validate_input():
user_input = entry.get()
if user_input.isdigit():
result_label.config(text=f"Valid Number: {user_input}")
else:
messagebox.showerror("Error", "Please enter a valid number!")

5acXjz Uk
root = tk.Tk()
root.title("Number Validator")

entry = tk.Entry(root)
entry.pack(pady=5)

btn_validate = tk.Button(root, text="Validate", command=validate_input)


btn_validate.pack(pady=5)

result_label = tk.Label(root, text="")


result_label.pack(pady=5)

root.mainloop()

Scenario 3: Radio Button Selection


Question:
Create a GUI app with three radio buttons for selecting a color. When selected, the background of
the window should change to that color.

Solution:

import tkinter as tk

def change_color():
color = color_var.get()
root.config(bg=color)

root = tk.Tk()
root.title("Color Selector")

color_var = tk.StringVar(value="white")

colors = ["Red", "Green", "Blue"]


for color in colors:
tk.Radiobutton(root, text=color, value=color.lower(),
variable=color_var, command=change_color).pack(pady=2)

root.mainloop()

Scenario 4: Checkbox Selection


Question:
Build a GUI app with three checkboxes: Python, Java, and C++. Display the selected options in a label
when a button is clicked.

Solution:

import tkinter as tk

def show_selection():
selected = []
if chk_python_var.get():

5acXjz Uk
selected.append("Python")
if chk_java_var.get():
selected.append("Java")
if chk_cpp_var.get():
selected.append("C++")

label_result.config(text="Selected: " + ", ".join(selected))

root = tk.Tk()
root.title("Checkbox Example")

chk_python_var = tk.BooleanVar()
chk_java_var = tk.BooleanVar()
chk_cpp_var = tk.BooleanVar()

tk.Checkbutton(root, text="Python", variable=chk_python_var).pack()


tk.Checkbutton(root, text="Java", variable=chk_java_var).pack()
tk.Checkbutton(root, text="C++", variable=chk_cpp_var).pack()

btn_show = tk.Button(root, text="Show Selection", command=show_selection)


btn_show.pack(pady=5)

label_result = tk.Label(root, text="Selected: ")


label_result.pack(pady=5)

root.mainloop()

Scenario 5: Listbox Selection


Question:
Create a GUI app with a Listbox that shows five fruit names. When a fruit is selected, display its
name in a label.

Solution:

import tkinter as tk

def show_selected():
selected_fruit = listbox.get(listbox.curselection())
label_result.config(text=f"Selected Fruit: {selected_fruit}")

root = tk.Tk()
root.title("Listbox Example")

fruits = ["Apple", "Banana", "Orange", "Grapes", "Mango"]


listbox = tk.Listbox(root)
for fruit in fruits:
listbox.insert(tk.END, fruit)

listbox.pack(pady=5)

btn_show = tk.Button(root, text="Show Selected", command=show_selected)


btn_show.pack(pady=5)

label_result = tk.Label(root, text="Selected Fruit: ")


label_result.pack(pady=5)

5acXjz Uk
root.mainloop()

Scenario 6: ComboBox Selection


Question:
Create a GUI app with a ComboBox that allows the user to select their favorite programming
language.

Solution:

import tkinter as tk
from tkinter import ttk

def display_choice():
label_result.config(text=f"Selected: {combo.get()}")

root = tk.Tk()
root.title("ComboBox Example")

combo = ttk.Combobox(root, values=["Python", "Java", "C++", "JavaScript"])


combo.pack(pady=5)
combo.set("Select Language")

btn_select = tk.Button(root, text="Show Selection", command=display_choice)


btn_select.pack(pady=5)

label_result = tk.Label(root, text="")


label_result.pack(pady=5)

root.mainloop()

Scenario 7: Slider Control


Question:
Create a GUI app with a Slider that adjusts the window’s background color based on intensity
(shades of gray).

Solution:

import tkinter as tk

def change_shade(value):
value = int(value)
color = f'#{value:02x}{value:02x}{value:02x}'
root.config(bg=color)

root = tk.Tk()
root.title("Slider Example")

slider = tk.Scale(root, from_=0, to=255, orient="horizontal",


command=change_shade)
slider.pack(pady=5)

5acXjz Uk
root.mainloop()

Scenario 8: Scrollbar Implementation


Question:
Create a text widget with a scrollbar that allows users to scroll through the text.

Solution:

import tkinter as tk

root = tk.Tk()
root.title("Scrollbar Example")

text_area = tk.Text(root, wrap='word', height=10, width=40)


text_area.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

scrollbar = tk.Scrollbar(root, command=text_area.yview)


scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

text_area.config(yscrollcommand=scrollbar.set)

for i in range(1, 101):


text_area.insert(tk.END, f"Line {i}\n")

root.mainloop()

Scenario 9: Canvas Drawing


Question:
Create a canvas where the user can draw simple lines by clicking and dragging the mouse.

Solution:

import tkinter as tk

def draw(event):
x, y = event.x, event.y
canvas.create_oval(x, y, x+2, y+2, fill="black")

root = tk.Tk()
root.title("Canvas Drawing")

canvas = tk.Canvas(root, width=400, height=300, bg="white")


canvas.pack()

canvas.bind("<B1-Motion>", draw)

root.mainloop()

5acXjz Uk
Scenario 10: Messagebox Example
Question:
Create a simple GUI with a button that shows a confirmation dialog.

Solution:

import tkinter as tk
from tkinter import messagebox

def show_message():
response = messagebox.askyesno("Confirm", "Do you want to continue?")
if response:
label_result.config(text="You clicked Yes!")
else:
label_result.config(text="You clicked No!")

root = tk.Tk()
root.title("Messagebox Example")

btn_confirm = tk.Button(root, text="Click Me", command=show_message)


btn_confirm.pack(pady=5)

label_result = tk.Label(root, text="")


label_result.pack(pady=5)

root.mainloop()

5acXjz Uk

You might also like