-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
534 lines (428 loc) · 19.6 KB
/
main.py
File metadata and controls
534 lines (428 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
import random
import tkinter as tk
from tkinter import ttk, messagebox
from PIL import Image, ImageTk
import sqlite3
# Database to store questions and answers
class Database:
def __init__(self):
self.conn = sqlite3.connect("database/quiz.db")
self.conn.row_factory = sqlite3.Row # Rows can be accessed as a dictionary
self.c = self.conn.cursor()
# Start the connection to the database
def open(self):
if self.conn is None:
self.conn = sqlite3.connect("database/quiz.db")
self.conn.row_factory = sqlite3.Row # Rows can be accessed as a dictionary
self.c = self.conn.cursor()
# End / close the connection to the databse
def close(self):
self.conn.commit()
self.conn.close()
self.conn = None
self.c = None
# Create a table
def table(self):
self.c.execute ("""
CREATE TABLE IF NOT EXISTS "quiz"(
"id" INTEGER,
"type" TEXT NOT NULL,
"question" TEXT NOT NULL,
"answer" TEXT NOT NULL,
"decoy_1" TEXT,
"decoy_2" TEXT,
"decoy_3" TEXT,
PRIMARY KEY("id")
)
""")
# Add a question
def add(self, type, question, answer, decoy_1=None, decoy_2=None, decoy_3=None):
table_values = ["type","question", "answer"] # It will hold the values from the table
questionmark_values =["?", "?", "?"] # It will hold the questionmarks
values = [type, question, answer] # It will hold the values that will be inserted into the placeholders
if decoy_1 is not None:
table_values.append("decoy_1")
questionmark_values.append("?")
values.append(decoy_1)
if decoy_2 is not None:
table_values.append("decoy_2")
questionmark_values.append("?")
values.append(decoy_2)
if decoy_3 is not None:
table_values.append("decoy_3")
questionmark_values.append("?")
values.append(decoy_3)
query = f'INSERT INTO "quiz"({", ".join(table_values)}) VALUES ({", ".join(questionmark_values)})'
self.c.execute (query, tuple(values))
# Delete a question
def delete(self, question):
self.c.execute('DELETE FROM "quiz" WHERE "question" = ?', (question,)) # 'question,' cause its a tuple
# Get questions based on the type selected
def type_questions(self, type):
self.c.execute('SELECT * FROM "quiz" WHERE "type" = ?', (type,))
return [dict(row) for row in self.c.fetchall()] # to get the values as json/dict
# Get a types which can be selected
def types(self):
self.c.execute('SELECT "type" FROM "quiz" GROUP BY "type"')
return [row["type"] for row in self.c.fetchall()] # to get the values as a list
# Count the number of questions in a type
def type_questions_count(self, type):
self.c.execute('SELECT COUNT(*) FROM "quiz" WHERE "type" = ?', (type,))
return self.c.fetchone()[0] # to get a number
# Tha main logic of the quiz
class Quiz:
# Essential attributes
def __init__(self):
self.score = 0
self.question_count = 0
self.questions = type_questions_list
self.current_question = None
# Start the quiz
def start(self):
# Reset the score and the question count
self.score = 0
self.question_count = 0
# Shuffle the questions
self.shuffle_questions()
# Return the first question
return self.next_question()
# Shuffle the questions order
def shuffle_questions(self):
random.shuffle(self.questions)
# Shuffle the answers for each question
def shuffle_answers(self, question):
answers_list = []
# Add the real answer to the list
answers_list.append(question["answer"])
# Add the decoys to the list if they exist
for i in ("decoy_1", "decoy_2", "decoy_3"):
if question.get(i):
answers_list.append(question[i])
# Shuffle the values added to the list
random.shuffle(answers_list)
return answers_list
# Check if the answer is correct and add to the score
def check_answer(self, users_answer):
if self.current_question:
if users_answer == self.current_question["answer"]:
self.score += 1
return True
return False
return False
# Start the next question and track the question count
def next_question(self):
# Check if all questions been asked
if self.question_count < len(self.questions):
# The current question
self.current_question = self.questions[self.question_count]
# Change the question count
self.question_count += 1
return self.current_question
# There are no more questions
else:
return None
# The current score count
def current_score(self):
return self.score
# The current question count
def current_question_count(self):
return self.question_count
# End/Finish the quiz
def end(self):
total = len(self.questions)
score_percentage = (self.score / total) * 100
return {
"score": self.score,
"total": total,
"percentage": score_percentage
}
# Main window
class Start_GUI:
# Start
def __init__(self):
self.open_window()
self.background()
self.title_buttons()
self.introduction()
# Create the window
def open_window(self):
global root
root = tk.Tk() # Creates the main application window
root.title("Quest for Python") # Window title
root.geometry("600x600") # Size
root.iconbitmap("images/main_icon.ico") # Icon
root.resizable(False, False) # Prevent resizing
# Set up the background
def background(self):
background = Image.open("images/background.jpg") # Background
background = background.resize((600, 600), Image.LANCZOS) # Resize
tk_background = ImageTk.PhotoImage(background) # Convert
background_label = tk.Label(root, image = tk_background) # Label
background_label.image = tk_background # Remains in memory
background_label.place(relwidth=1, relheight=1) # Fully cover the window
# The title and the buttons used on this page
def title_buttons(self):
title_label = tk.Label(root, text="Quest for Python", font=("Arial", 30, "bold"), fg="#fdf4ff", bg="#1b1037") # Display the title
title_label.place(x=140, y=50) # Placement
# Add and Delete Button
add_delete_button = tk.Button(root, text="Add & Delete", command=self.add_delete_window, font=("Arial", 16, "bold"), bg="#5d5dff", fg="#ffffff")
add_delete_button.place(x=395, y=500)
# Quiz Button
quiz_button = tk.Button(root, text="Quiz", command=self.quiz_window, font=("Arial", 16, "bold"), bg="#5d5dff", fg="#ffffff")
quiz_button.place(x=55, y=500)
# The introduction text
def introduction(self):
description = (
"Welcome to Quest for Python!\n"
"Test your knowledge, challenge yourself to learn more!\n"
"\n"
"This is a customizable quiz app where you can:\n"
"- Use the questions already given\n"
"- Choose from categories\n"
"- Create new questions\n"
"- Remove the questions you no longer need\n"
"- Track your progress\n"
"\n"
"Start by clicking the 'Quiz' or 'Add & Delete' to customize your questions."
)
# Frame for the text
frame = tk.Frame(root, bg="#1b1037", bd=2, relief="groove")
frame.place(x=65, y=170, width=470, height=250)
# Settings for the text
message = tk.Message(frame, text=description, font=("Arial", 11, "bold"), fg="#fdf4ff", bg="#1b1037", width=480, justify="center")
message.pack(padx=10, pady=10)
# Call on the Add_Delete_GUI class
def add_delete_window(self):
Add_Delete_GUI()
# Call on the Quiz_GUI class
def quiz_window(self):
Quiz_GUI()
# Add and Delete window
class Add_Delete_GUI:
# Start
def __init__(self):
self.open_window()
self.background()
self.labels_entries_buttons()
# Create the window
def open_window(self):
self.window = tk.Toplevel(root) # Child window for the root
self.window.title("Add & Delete questions") # Title
self.window.geometry("400x500") # Size
self.window.iconbitmap("images/main_icon.ico") # Icon
self.window.resizable(False, False) # Prevent resizing
# Connect to the database and make sure the table exists
self.db = Database()
self.db.table()
# Set up the background
def background(self):
background = Image.open("images/add_delete_background.jpg") # Background
background = background.resize((400, 500), Image.LANCZOS) # Resize
tk_background = ImageTk.PhotoImage(background) # Convert
background_label = tk.Label(self.window, image = tk_background) # Label
background_label.image = tk_background # Remains in memory
background_label.place(relwidth=1, relheight=1) # Fully cover the window
# Placement of all the buttons, entries and labels
def labels_entries_buttons(self):
# Add Question section
title_label = tk.Label(self.window, text="Add Question", font=("Arial", 16, "bold"), fg="black", bg="#C084FF") # Title
title_label.place(x=135, y=20)
fields = ["Type", "Question", "Answer", "Decoy 1", "Decoy 2", "Decoy 3"]
# Add the entries here, so we can use it in the add_question function
self.add_entries = []
# Label and entry for each field
for i, field in enumerate(fields):
label = tk.Label(self.window, text=field, fg="black", bg="#C97EBB", font=("Arial", 12, "bold"))
label.place(x=25, y=70 + i*40)
entry = tk.Entry(self.window, width=43)
entry.place(x=110, y=70 + i*40)
self.add_entries.append(entry)
# Button
tk.Button(self.window, text="Add Question", command=self.add_question, bg="#DA70D6", fg="black").place(x=160, y=300)
# Delete Question section
title_label = tk.Label(self.window, text="Delete Question", font=("Arial", 16, "bold"), fg="black", bg="#C084FF") # Title
title_label.place(x=120, y=350)
# Label and entry to delete a question
delete_label = tk.Label(self.window, text="Question", fg="black", bg="#C97EBB", font=("Arial", 12, "bold"))
delete_label.place(x=25, y=400)
self.delete_entry = tk.Entry(self.window, width=43)
self.delete_entry.place(x=110, y=400)
# Button
tk.Button(self.window, text="Delete Question", command=self.delete_question, bg="#DA70D6", fg="black").place(x=152, y=440)
# Adding a question
def add_question(self):
# Get what is written in each entry; the decoys are not required
type = self.add_entries[0].get().strip()
question = self.add_entries[1].get().strip()
answer = self.add_entries[2].get().strip()
decoy_1 = self.add_entries[3].get().strip() or None
decoy_2 = self.add_entries[4].get().strip() or None
decoy_3 = self.add_entries[5].get().strip() or None
# Check if the required entries are filled
if not (type and question and answer):
self.feedback_message("Please fill in the Type, Question, and Answer.", "Warning")
return
# Add the question to the database
try:
# Open the database if it's not already open
self.db.open()
self.db.add(
type = type,
question = question,
answer = answer,
decoy_1 = decoy_1 if decoy_1 else None,
decoy_2 = decoy_2 if decoy_2 else None,
decoy_3 = decoy_3 if decoy_3 else None
)
self.feedback_message("The question is successfully added!", "Info")
# Commit the changes and close the database
self.db.close()
# Delete the entries from the list
for entry in self.add_entries:
entry.delete(0, tk.END)
# Check for errors
except sqlite3.Error as e:
self.feedback_message(f"A database error occurred: {e}", "Error")
except Exception as e:
self.feedback_message(f"An error occurred while adding the question: {e}", "Error")
# Delete a question
def delete_question(self):
# Get the entry to delete the question
question = self.delete_entry.get().strip()
# Check if there is a question added
if not question:
self.feedback_message("Please enter the question you want to delete.", "Warning")
return
try:
# Open the database if it's not already open
self.db.open()
# Check if the question exists before deleting it
self.db.c.execute('SELECT * FROM "quiz" WHERE "question" = ?', (question,))
if not self.db.c.fetchone():
self.feedback_message("This question doesn't exist in the database.", "Warning")
return
# Delete the question
self.db.delete(question)
# Commit and close the database
self.db.close()
self.feedback_message("The question is successfully deleted!", "Info")
# Delete the entry
self.delete_entry.delete(0, tk.END)
# Check for errors
except sqlite3.Error as e:
self.feedback_message(f"A database error occurred: {e}", "Error")
except Exception as e:
self.feedback_message(f"An error occurred while deleting the question: {e}", "Error")
# Feedback message
def feedback_message(self, message, type):
if type == "Info":
messagebox.showinfo("Info", message)
elif type == "Warning":
messagebox.showwarning("Warning", message)
elif type == "Error":
messagebox.showerror("Error", message)
# Quiz window
class Quiz_GUI:
def __init__(self):
self.open_window()
self.background()
self.choose_type()
# Create the window
def open_window(self):
self.window = tk.Toplevel(root) # Child window for the root
self.window.title("Quiz") # Title
self.window.geometry("500x600") # Size
self.window.iconbitmap("images/main_icon.ico") # Icon
self.window.resizable(False, False) # Prevent resizing
# Connect to the database
self.db = Database()
self.db.open()
# Set up the background
def background(self):
background = Image.open("images/quiz_background.jpg") # Background
background = background.resize((500, 600), Image.LANCZOS) # Resize
tk_background = ImageTk.PhotoImage(background) # Convert
background_label = tk.Label(self.window, image=tk_background) # Label
background_label.image = tk_background # Remains in memory
background_label.place(relwidth=1, relheight=1) # Fully cover the window
# Choose the type and start the quiz
def choose_type(self):
# Dropdown menu for types
type_label = tk.Label(self.window, text="Choose Type:", font=("Arial", 12, "bold"), bg="#e4c1f9")
type_label.place(x=30, y=30)
self.type_var = tk.StringVar() # Store the currently selected value
self.type_dropdown = ttk.Combobox(self.window, textvariable=self.type_var, state="readonly", width=30) # Dropdown menu
self.type_dropdown['values'] = self.db.types() # Get all the type names from the Database class
self.type_dropdown.place(x=150, y=30)
# Start Button
start_button = tk.Button(self.window, text="Start Quiz", command=self.start_quiz, bg="#b5ead7", font=("Arial", 11, "bold"))
start_button.place(x=200, y=70)
# Frame to hold the questions and answers
self.questioning_frame = tk.Frame(self.window, bg="#1c0030", bd=2, relief="sunken", highlightbackground="#8be9fd", highlightthickness=1)
self.questioning_frame.place(x=30, y=120, width=440, height=400)
# Start the quiz
def start_quiz(self):
chosen_type = self.type_var.get()
if not chosen_type:
messagebox.showwarning("Warning", "Please select a type.")
return
# Get the questions from the Database
global type_questions_list
type_questions_list = self.db.type_questions(chosen_type)
if not type_questions_list:
messagebox.showinfo("Info", "No questions found for the selected type.")
return
# Initialize quiz logic and start with the first question
self.quiz = Quiz()
self.show_question(self.quiz.start())
# Show the questions, one at a time
def show_question(self, question):
for widget in self.questioning_frame.winfo_children(): # Add answer to questioning_frame
widget.destroy() # Clear the previous question
# Display the question
if question:
question_label = tk.Label(self.questioning_frame, text=question['question'], wraplength=400, font=("Arial", 12, "bold"), fg="#a3a3c2", bg="#1c0030")
question_label.pack(pady=20)
# Shuffle the answers and display them as buttons
answers = self.quiz.shuffle_answers(question)
for answer in answers:
buttons = tk.Button(self.questioning_frame, text=answer, font=("Arial", 11), width=40, bg="#2e003e", fg="#d6d6f5", command=lambda a=answer: self.check_answer(a))
buttons.pack(pady=5)
# If there are no more questions left the game is finished
else:
self.show_results()
# Check if the answers are correct
def check_answer(self, selected):
correct = self.quiz.check_answer(selected)
# Disable all buttons during the feedback, make the selected answer red(wrong answer) or green(right answer)
for button in self.questioning_frame.winfo_children():
if isinstance(button, tk.Button):
button.config(state="disabled")
# Highlight the answers background to red or green
if button.cget("text") == selected:
button.config(bg="#f28b82" if not correct else "#81c784")
# Highlights with green the correct answer
elif button.cget("text") == self.quiz.current_question['answer']:
button.config(bg="#81c784")
# Wait 2 seconds before showing the next question
self.window.after(2000, lambda: self.show_question(self.quiz.next_question()))
# Finish - show the results
def show_results(self):
# Clear the question area
for widget in self.questioning_frame.winfo_children():
widget.destroy()
# Get the result
result = self.quiz.end()
summary = (
f"🌟 Finished! 🌟\n\n"
f"Correct Answers: {result['score']} out of {result['total']}\n"
f"Score Percentage: {result['percentage']:.2f}%"
)
result_label = tk.Label(self.questioning_frame, text=summary, font=("Arial", 16, "bold"), fg="#4caf50", bg="#1c0030", justify="center", wraplength=400)
result_label.pack(pady=100)
# Start the program
def main():
Start_GUI() # Open the start graphicat user interface
root.mainloop() # Run it
if __name__ == "__main__":
main()