-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quizzel.pyw
1701 lines (1519 loc) · 79.1 KB
/
Quizzel.pyw
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Quizzel by Nikesh Purohit 2017
from tkinter import *
import tkinter.ttk as ttk
import sqlite3, sys, time, hashlib, tkinter.messagebox, random, urllib.request, ftplib
database = sqlite3.connect('database.db')
cursor = database.cursor()
def h():
global database, cursor
#url = urllib.request.urlretrieve('http://quizzel.x10.mx/database.db')
database = None
#database = sqlite3.connect(url[0])
database = sqlite3.connect('Quizzel files/database.db')
cursor = None
cursor = database.cursor()
def ConnectFTP():
#global ftp_connection
#server = 'ftp.quizzel.x10.mx'
#username = 'database@quizzel.x10.mx'
#password = '^ArvSiq1&;tx'
#ftp_connection = None
#ftp_connection = ftplib.FTP(server, username, password)
return True
def u():
if WaitForUnlock():
#lockfile = open("Quizzel files/lock", "rb")
#ftp_connection.storbinary('STOR ' + 'lock', lockfile)
#d = open(url[0], "rb")
#ftp_connection.storbinary('STOR ' + 'database.db', d)
#ftp_connection.delete("lock")
return True
def WaitForUnlock():
#if "lock" in ftp_connection.nlst():
# return WaitForUnlock()
#else:
# return True
return True
class Splash(Toplevel):
def __init__(self, parent):
Toplevel.__init__(self, parent)
canvas = Canvas(self)
background = PhotoImage(file="Quizzel files/splash2.png")
self.overrideredirect(1)
self.configure(bg="white")
width = 764
height = 460
x = (self.winfo_screenwidth() // 2) - (width // 2)
y = (self.winfo_screenheight() // 2) - (height // 2)
self.geometry('{}x{}+{}+{}'.format(width, height, x, y))
canvas.create_image(0, 0, image=background, anchor="nw")
canvas.image = background
canvas.pack(expand=1, fill=BOTH, side=TOP)
self.update()
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.withdraw()
splash = Splash(self)
#try:
#
# ConnectFTP()
# Splash.destroy(splash)
# self.deiconify()
#except:
# Splash.destroy(splash)
# tkinter.messagebox.showerror("Quizzel cannot start", "Could not connect to database. Please ensure you have a working internet connection.")
# sys.exit(0)
ConnectFTP()
Splash.destroy(splash)
self.deiconify()
self.configure(bg="white")
self.geometry("1100x650+100+50")
#self.iconbitmap(r'Quizzel files/icon3.ico')
container = Frame(self, bg='white')
container.pack(side="top", fill=BOTH, expand=False)
self.FirstTime = None
self.ButtonColour = "#626262"
self.labelcolour = "black"
self.QuizIDSearch = []
self.QuizItems = []
self.Name = StringVar()
self.YearGroup = StringVar()
self.Username = StringVar()
self.Teacher = StringVar()
self.TargetGrade = StringVar()
self.Subjects = StringVar()
self.Results = []
self.ChooserList = []
self.UserDetailsList = []
self.ChosenQuiz = None
self.QuestionStack = []
self.CurrentQuestion = 0
self.Score = 0
self.MaxScore = 0
self.ChosenQuizTitle = None
self.UserID = None
self.WrongQuestion = []
self.QuestionID = []
self.WrongAnswer = []
self.AllQID = []
self.ShouldSave = False
self.ModifyChooserList = []
self.ModifyQuizID = 0
self.ModifyUserList = []
self.ModifyUserID = 0
self.imgLogo = PhotoImage(file="Quizzel files/toplogosmallest.png")
self.frameTopBanner = Frame(self, bg="#2b3033")
self.lblTopLogo = Label(self.frameTopBanner, bg="#2b3033", fg="white", font=("Arial", 16, 'bold'), text="Quizzel", image=self.imgLogo)
self.lblTopLogo.photo = self.imgLogo
self.lblTopLogo.pack(anchor=CENTER, padx=9, pady=9)
self.frameTopBanner.pack(side=TOP, fill=X)
self.frames = {}
self.PackFrame(frameLoginPage, container)
def PackFrame(self, F, container):
frame = F(container, self)
self.frames[F] = frame
frame.pack(expand=1, side=TOP)
class frameFirstTime(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")
controller.title("Quizzel - Create Password")
time_string = time.strftime('%d/%m/%Y, %H:%M')
labeltext = "Welcome to your new Quizzel account! Before you can start using Quizzel, you must create a password. You can change your password later in settings. Once you have created your password, click continue to proceed to the tutorial on how to make the most of Quizzel."
BoxVar1 = StringVar()
BoxVar2 = StringVar()
def Continue():
cont = ChangePassword()
if cont:
if root.Teacher == 0:
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameStudentMenu, parent)
parent.pack(expand=1, fill=BOTH)
if root.Teacher == 1:
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameTeacherMenu, parent)
parent.pack(expand=1, fill=BOTH)
def CheckBoxes():
global newpass
emptyhash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
new1 = BoxVar1.get().encode('utf-8')
h = hashlib.sha256()
h.update(new1)
new1 = h.hexdigest()
new2 = BoxVar2.get().encode('utf-8')
h = hashlib.sha256()
h.update(new2)
new2 = h.hexdigest()
if new1 != emptyhash and new2 !=emptyhash:
if new1 == new2:
newpass = new1
boxNewPassword1.configure(bg="#cee1ff")
boxNewPassword2.configure(bg="#cee1ff")
return True
else:
lblOutput.configure(text="New passwords do not match.", fg="#bc0000")
boxNewPassword1.configure(bg="#bc0000")
boxNewPassword2.configure(bg="#bc0000")
return False
else:
lblOutput.configure(text="Password field can not be left empty.", fg="#bc0000")
if new1 == emptyhash:
boxNewPassword2.configure(bg="#cee1ff")
boxNewPassword1.configure(bg="#bc0000")
if new2 == emptyhash:
boxNewPassword1.configure(bg="#cee1ff")
boxNewPassword2.configure(bg="#bc0000")
if new1 == emptyhash and new2 == emptyhash:
boxNewPassword1.configure(bg="#bc0000")
boxNewPassword2.configure(bg="#bc0000")
return False
def ChangePassword():
allowed = CheckBoxes()
if allowed:
cursor.execute('''UPDATE users SET password=? WHERE UserID=? ''',(newpass,root.UserID))
cursor.execute('''UPDATE users SET FirstTime=0 WHERE UserID=?''', (root.UserID,))
database.commit()
lblOutput.configure(text="Password changed successfully!", fg="green")
boxNewPassword1.delete(0, END)
boxNewPassword2.delete(0, END)
return True
else:
BoxVar1 = StringVar()
BoxVar2 = StringVar()
return False
lblText = Label(self, text=labeltext, bg="white", fg="#04286f", font=("Arial", 14, ''), wraplength=800)
lblOutput = Label(self, text="", bg="white", fg="red", font=("Arial", 12, ''))
boxNewPassword1 = Entry(self, textvariable=BoxVar1, relief=FLAT, bg="#cee1ff", width=40, show="●")
boxNewPassword2 = Entry(self, textvariable=BoxVar2, relief=FLAT, bg="#cee1ff", width=40, show="●")
lblBox1 = Label(self, text="New password:", bg="white", fg="#04286f", font=("Arial", 12, ''))
lblBox2 = Label(self, text="Confirm new password:", bg="white", fg="#04286f", font=("Arial", 12, ''))
btnContinue = Button(self, command=Continue, text='Continue >', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
lblText.grid(columnspan=2, row=0)
lblOutput.grid(pady=4, columnspan=2, row=1)
boxNewPassword1.grid(pady=4, column=1, row=3, sticky=E)
boxNewPassword2.grid(pady=7, column=1, row=4, sticky=E)
lblBox1.grid(pady=4, column=0, row=3, sticky=E)
lblBox2.grid(pady=7, column=0, row=4, sticky=E)
btnContinue.grid(pady=10, columnspan=2)
class frameLoginPage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")
controller.title("Quizzel - Login")
def LoginButton(event):
u = username.get()
p = password.get().encode('utf-8')
h = hashlib.sha256()
h.update(p)
p = h.hexdigest()
LoggedIn = False
LoggedIn = Login(u,p)
if LoggedIn == True:
controller.unbind('<Return>')
controller.unbind('<Button-1>')
controller.unbind('<space>')
if root.FirstTime == 0:
if root.Teacher == 0:
controller.PackFrame(frameStudentMenu, parent)
parent.pack_forget()
self.pack_forget()
parent.pack(expand=1, fill=BOTH)
if root.Teacher == 1:
controller.PackFrame(frameTeacherMenu, parent)
parent.pack_forget()
self.pack_forget()
parent.pack(expand=1, fill=BOTH)
if root.FirstTime == 1:
controller.PackFrame(frameFirstTime, parent)
parent.pack_forget()
self.pack_forget()
parent.pack(expand=1, fill=BOTH)
def Login(u,p):
global loginlabel2colour, found
cursor.execute('''SELECT * FROM Users WHERE Username=? AND Password=? ''',(u,p))
found = cursor.fetchone()
if found:
cursor.execute('''SELECT UserID FROM Users WHERE Username=? AND Password=? ''',(u,p))
UserID = cursor.fetchone()
GetUserDetails(UserID)
loginlabel2.set("Login successful!")
loginlabel2colour = "#04286f"
lblOutput = Label(self, textvariable=loginlabel2, bg="white", fg=loginlabel2colour, font=("Arial", 13, ''))
lblOutput.grid(row = 1, pady=0)
boxUsername.delete(0, END)
boxPassword.delete(0, END)
return True
else:
loginlabel2.set("The username or password is incorrect, please try again.")
loginlabel2colour = "#bc0000"
lblOutput = Label(self, textvariable=loginlabel2, bg="white", fg=loginlabel2colour, font=("Arial", 13, ''))
lblOutput.grid(row = 1, pady=0)
boxPassword.delete(0, END)
controller.bell()
return False
def GetUserDetails(UserID):
UserID = str(UserID)
for s in ['(', ')', ',']:
UserID = UserID.strip(s)
cursor.execute("SELECT Name, YearGroup, Username, Teacher, TargetGrade, Subjects, FirstTime FROM users WHERE UserID=?",(UserID,))
for column in cursor:
root.UserDetailsList.append((column[0],column[1],column[2],column[3],column[4],column[5],column[6]))
root.Name = root.UserDetailsList[0][0]
root.YearGroup = root.UserDetailsList[0][1]
root.Username = root.UserDetailsList[0][2]
root.Teacher = root.UserDetailsList[0][3]
root.TargetGrade = root.UserDetailsList[0][4]
root.Subjects = root.UserDetailsList[0][5]
root.FirstTime = root.UserDetailsList[0][6]
if root.Subjects != None:
root.Subjects = root.Subjects.split(", ")
root.UserID = UserID
controller.bind('<Return>',LoginButton)
global loginlabel2
imgArrow = PhotoImage(file="Quizzel files/loginbuttonsmall.png")
loginlabel2 = StringVar()
loginlabel2.set("Please enter your username and password to login: ")
loginlabel2colour = "#282828"
password = StringVar()
username = StringVar()
lblWelcome = Label(self, text="Welcome to Quizzel!", bg="white", fg="#282828", font=("Arial", 16, 'bold'))
lblWelcome.grid(row = 0, pady=9)
lblOutput = Label(self, textvariable=loginlabel2, bg="white", fg=loginlabel2colour, font=("Arial", 13, ''))
lblOutput.grid(row = 1, pady=0)
boxUsername = Entry(self, textvariable=username, relief=FLAT, bg="#87B2F3", width=40)
boxUsername.grid(row = 2, pady=5)
boxPassword = Entry(self, textvariable=password, relief=FLAT, bg="#87B2F3", show="●", width=40)
boxPassword.grid(row = 3, pady=5)
btnLogin = Button(self, text='Login', relief=FLAT, overrelief=FLAT, bg="white", fg="#04286f", image=imgArrow, activebackground="white", highlightthickness="0")
btnLogin.photo = imgArrow
btnLogin.grid(row = 4, pady=9)
btnLogin.focus_force()
btnLogin.bind('<Button-1>',LoginButton)
btnLogin.bind('<space>',LoginButton)
class frameStudentMenu(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent, bg="white", highlightthickness=0)
controller.title("Quizzel - Student (%s, Year %s)" % (root.Name, root.YearGroup))
def ChooseQuizButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameQuizSelection, parent)
parent.pack(expand=1)
def ResultsButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameResultsStudent, parent)
parent.pack(expand=1)
def SettingsButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(framePasswordChange, parent)
parent.pack(expand=1)
def Logout():
loginlabel2.set("Please enter your username and password to login: ")
found = False
LoggedIn = False
root.ChooserList = []
root.QuizIDSearch = []
root.QuizItems = []
root.Name = StringVar()
root.YearGroup = StringVar()
root.Username = StringVar()
root.Teacher = StringVar()
root.TargetGrade = StringVar()
root.Subjects = StringVar()
root.Results = []
root.ChooserList = []
root.UserDetailsList = []
root.ChosenQuiz = None
root.QuestionStack = []
root.CurrentQuestion = 0
root.Score = 0
root.MaxScore = 0
root.ChosenQuizTitle = None
root.UserID = None
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameLoginPage, parent)
QuizButton = Button(self, command=ChooseQuizButton, text='Take A Quiz', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='43', pady='22')
ResultsButton = Button(self, command=ResultsButton, text='See your results', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='43', pady='22')
SettingsButton = Button(self, command=SettingsButton, text='Settings', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='43', pady='22')
LogoutButton = Button(self, command=Logout, text='Logout', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='43', pady='22')
QuizButton.grid(pady=18)
ResultsButton.grid(pady=18)
SettingsButton.grid(pady=18)
LogoutButton.grid(pady=18)
class frameTeacherMenu(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent, bg="white")
controller.title("Quizzel - Teacher (%s)" % root.Name)
def mQuiz():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameModifyQuizSelector, parent)
parent.pack(expand=1)
def TeacherResultsButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameResultsTeacher, parent)
parent.pack(expand=1)
def ModifyUsersButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameModifyUser, parent)
parent.pack(expand=1)
def SubjectButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameNewSubject, parent)
parent.pack(expand=1)
def Logout():
loginlabel2.set("Please enter your username and password to login: ")
found = False
LoggedIn = False
root.ChooserList = []
root.QuizIDSearch = []
root.QuizItems = []
root.Name = StringVar()
root.YearGroup = StringVar()
root.Username = StringVar()
root.Teacher = StringVar()
root.TargetGrade = StringVar()
root.Subjects = StringVar()
root.Results = []
root.ChooserList = []
root.UserDetailsList = []
root.ChosenQuiz = None
root.QuestionStack = []
root.CurrentQuestion = 0
root.Score = 0
root.MaxScore = 0
root.ChosenQuizTitle = None
root.UserID = None
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameLoginPage, parent)
btnModifyQuiz = Button(self, command=mQuiz, text='Create/Modify Quiz', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='43', pady='22')
btnResults = Button(self, command=TeacherResultsButton, text='See student results', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='43', pady='22')
btnManageUsers = Button(self, command=ModifyUsersButton, text='Add / Remove Users', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='43', pady='22')
btnAddSubject = Button(self, command=SubjectButton, text='Add New Subject', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='43', pady='22')
btnLogout = Button(self, command=Logout, text='Logout', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='43', pady='22')
btnModifyQuiz.grid(pady=18)
btnResults.grid(pady=18)
btnManageUsers.grid(pady=18)
btnAddSubject.grid(pady=18)
btnLogout.grid(pady=18)
class frameResultsTeacher(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")
reverse = False
def TeacherMenuButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameTeacherMenu, parent)
parent.pack(expand=1, fill=BOTH)
def PopulateResults(sort):
root.Results = []
for i in tree.get_children():
tree.delete(i)
cursor.execute('SELECT UserID, QuizID, Result, Time FROM results')
for column in cursor:
root.Results.append([column[0],column[1],column[2],column[3]])
for j in range (0, len(root.Results)):
QuizID = root.Results[j][1]
cursor.execute('SELECT QuizTitle from quizzes where QuizID=?',(QuizID,))
k = cursor.fetchone()
for s in ['(', ')', ',',"'"]:
k = str(k).strip(s)
root.Results[j][1] = k
for u in range (0, len(root.Results)):
UserID = root.Results[u][0]
cursor.execute('SELECT Name from users where UserID=?',(UserID,))
h = cursor.fetchone()
for s in ['(', ')', ',',"'"]:
h = str(h).strip(s)
root.Results[u][0] = h
if sort == "reverse":
ReverseList(root.Results)
if sort == "byname":
root.Results = sorted(root.Results, key=lambda x: (x[0]))
for item in root.Results:
tree.insert('', 'end', values=item)
def ReverseList(l, first=0, last=-1):
if first >= len(l)/2:
return
l[first], l[last] = l[last], l[first]
ReverseList(l, first+1, last-1)
def SortA(l): #IMPLEMENT THIS CODE
if len(l) == 1:
return True
elif l[0] <= l[1]:
return SortA(l[1:])
else:
return False
def SortAlphabetically(l): #IMPLEMENT THIS CODE
if len(l) == 1:
return
elif l[0][0] <= l[1][0]:
return SortAlphabetically(l[1:][0])
else:
return
def CheckSort(event):
if sortvar.get() == "Newest first":
PopulateResults("reverse")
if sortvar.get() == "Oldest first":
PopulateResults("none")
if sortvar.get() == "Name (A-Z)":
PopulateResults("byname")
sortvar=StringVar()
lblSort = Label(self, text="Sort by:", bg="white", fg="#04286f", font=("Arial", 13, ''), wraplength="850")
sortvar.set("Oldest first")
comboSort = ttk.Combobox(self, textvariable=sortvar, state='readonly')
comboSort['values'] = ('Oldest first','Newest first','Name')
comboSort.bind('<<ComboboxSelected>>', CheckSort)
frameTree = Frame(self)
tree = ttk.Treeview(frameTree)
tree["columns"] = ("one", "two", "three", "four")
tree['show'] = 'headings'
tree.column("one", width=100)
tree.column("two", width=500)
tree.column("three", width=100)
tree.column("four", width=200)
tree.heading("one", text="Student")
tree.heading("two", text="Quiz Title")
tree.heading("three", text="Result")
tree.heading("four", text="Completed on")
ysb = ttk.Scrollbar(orient=VERTICAL, command=tree.yview)
tree['yscroll'] = ysb.set
ysb.grid(in_=frameTree, row=0, column=1, sticky=NS)
frameTree.grid(row=3, columnspan=100, pady=9)
tree.grid(in_=frameTree, row=0, column=0, sticky=NSEW)
btnMenu = Button(self, command=TeacherMenuButton, text='< Back to Menu', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
btnMenu.grid(row=4, columnspan=100)
lblSort.grid(row=0, column=49, pady=10)
comboSort.grid(row=0, column=50, pady=10)
PopulateResults(reverse)
#
print("BEFORE ",root.Results)
SortAlphabetically(root.Results)
print(" ")
print(sorted(root.Results,key=lambda x: (x[0])))
#print("AFTER ",root.Results)
#
class frameQuizSelection(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")
def MenuButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameStudentMenu, parent)
parent.pack(expand=1, fill=BOTH)
def MultiQuizButton():
ChooserListIndex = listboxQuiz.index(ACTIVE)
QuizID = root.ChooserList[ChooserListIndex][0]
root.ChosenQuiz = QuizID
cursor.execute("SELECT QuizTitle FROM quizzes WHERE QuizID=?",(root.ChosenQuiz,))
root.ChosenQuizTitle = cursor.fetchone()
self.pack_forget()
parent.pack_forget()
controller.PackFrame(framePreQuiz, parent)
parent.pack(expand=1, fill=BOTH)
def FillQuizList():
root.QuizItems = []
root.ChooserList = []
root.QuizIDSearch = []
cursor.execute('SELECT QuizID FROM Quizzes')
AllQuizzes = cursor.fetchall()
for i in AllQuizzes:
i = i[0]
for SubID in root.Subjects:
cursor.execute('''SELECT QuizTitle FROM Quizzes WHERE QuizID=? AND SubjectID=? ''',(i,SubID))
QuizName = cursor.fetchone()
cursor.execute('''SELECT SubjectName FROM Subjects WHERE SubjectID=?''',SubID)
SubjectName = cursor.fetchall()
cursor.execute('''SELECT QuizID FROM Quizzes WHERE QuizID=? AND SubjectID=? ''',(i,SubID))
QuizID = cursor.fetchone()
try:
SubjectName = SubjectName[0][0]
except:
tkinter.messagebox.showerror("SubjectName[0][0] Failed","One or more of your subject(s) are not valid. You may have been entered for a subject that does not exist.")
self.pack_forget()
parent.pack_forget()
frameStudentMenu.pack(self)
parent.pack(expand=1, fill=BOTH)
return
if QuizName != None:
root.ChooserList.append(QuizID)
QuizName = str(QuizName[0])
ListItem = "%s - %s" %(SubjectName,QuizName)
listboxQuiz.insert(END, ListItem)
root.QuizItems.append(ListItem)
root.QuizIDSearch.append(QuizName)
def SearchListBox():
root.ChooserList = []
root.QuizIDSearch = []
QuizItems = []
search_term = search_var.get()
if search_term == "":
FillQuizList()
listboxQuiz.delete(0, END)
for item in root.QuizItems:
if search_term.lower() in item.lower():
listboxQuiz.insert(END, item)
QuizItems = listboxQuiz.get(0, END)
for z in QuizItems:
z = z.split(' - ')
z = z[1]
root.QuizIDSearch.append(z)
for i in root.QuizIDSearch:
cursor.execute('SELECT QuizID FROM Quizzes WHERE QuizTitle=?',(i,))
QuizID = cursor.fetchone()
for s in ['(', ')', ',']:
QuizID = str(QuizID).strip(s)
root.ChooserList.append(QuizID)
search_var = StringVar()
search_var.trace("w", lambda name, index, mode: SearchListBox())
boxSearch = Entry(self, textvariable=search_var, relief=FLAT, bg="#cee1ff", width=40)
lblQuizList = Label(self, text="Please select a Quiz from the list below or search: ", bg="white", fg="#04286f", font=("Arial", 13, 'bold'))
listboxQuiz = Listbox(self, width=110, height=20)
btnSelect = Button(self, command=MultiQuizButton, text='Proceed to Quiz >', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
btnMenu = Button(self, command=MenuButton, text='< Back to Menu', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
FillQuizList()
boxSearch.grid(row=2, columnspan=6, pady=19)
lblQuizList.grid(row=1, pady=9, columnspan=6)
listboxQuiz.grid(columnspan=6, pady=3)
btnMenu.grid(pady=17, column=0, row=5)
btnSelect.grid(pady=17, column=5, row=5)
class frameResultsStudent(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")
reverse = False
def MenuButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameStudentMenu, parent)
parent.pack(expand=1, fill=BOTH)
def PopulateResults(r):
reverse = r
root.Results = []
for i in tree.get_children():
tree.delete(i)
cursor.execute('SELECT QuizID, Result, Time FROM results where UserID=?', (root.UserID,))
for column in cursor:
root.Results.append([column[0],column[1],column[2]])
for j in range (0, len(root.Results)):
QuizID = root.Results[j][0]
cursor.execute('SELECT QuizTitle from quizzes where QuizID=?',(QuizID,))
k = cursor.fetchone()
for s in ['(', ')', ',',"'"]:
k = str(k).strip(s)
root.Results[j][0] = k
if reverse == True:
ReverseList(root.Results)
for item in root.Results:
tree.insert('', 'end', values=item)
NameLabelText = StringVar()
YearLabelText = StringVar()
TargetLabelText = StringVar()
Name = root.Name
YearGroup = root.YearGroup
TargetGrade = root.TargetGrade
NameLabelText.set(str("Name: "+Name+""))
YearLabelText.set(str("Year: "+str(YearGroup)+""))
TargetLabelText.set(str("Target Grade: " +TargetGrade))
frameTree = Frame(self)
tree = ttk.Treeview(frameTree)
tree["columns"] = ("one", "two", "three")
tree['show'] = 'headings'
tree.column("one", width=500)
tree.column("two", width=100)
tree.column("three", width=200)
tree.heading("one", text="Quiz Title")
tree.heading("two", text="Result")
tree.heading("three", text="Completed on")
ysb = ttk.Scrollbar(orient=VERTICAL, command=tree.yview)
tree['yscroll'] = ysb.set
ysb.grid(in_=frameTree, row=0, column=1, sticky=NS)
frameTree.grid(row=2, columnspan=100)
tree.grid(in_=frameTree, row=0, column=0, sticky=NSEW)
def ReverseList(l, first=0, last=-1):
if first >= len(l)/2:
return
l[first], l[last] = l[last], l[first]
ReverseList(l, first+1, last-1)
def CheckSort(event):
if sortvar.get() == "Newest first":
reverse = True
PopulateResults(reverse)
else:
reverse = False
PopulateResults(reverse)
sortvar=StringVar()
lblSort = Label(self, text="Sort by:", bg="white", fg="#04286f", font=("Arial", 13, ''), wraplength="850")
sortvar.set("Oldest first")
comboSort = ttk.Combobox(self, textvariable=sortvar, state='readonly')
comboSort['values'] = ('Oldest first','Newest first')
comboSort.bind('<<ComboboxSelected>>', CheckSort)
btnMenu = Button(self, command=MenuButton, text='< Back to Menu', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
btnMenu.grid(row=3, columnspan=100)
lblSort.grid(row=0, column=49, pady=10)
comboSort.grid(row=0, column=50, pady=10)
PopulateResults(reverse)
class framePreQuiz(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")
root.title("Quizzel - %s" % (root.ChosenQuizTitle))
def MenuButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameQuizSelection, parent)
parent.pack(expand=1, fill=BOTH)
def ProceedButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameQuiz, parent)
parent.pack(expand=1, fill=BOTH)
lblHeading = Label(self, text="On your marks...", bg="white", fg="blue", font=("Arial", 15, 'bold'))
lblQuizTitle = Label(self, text="You are about to take: %s" % (root.ChosenQuizTitle[0]), bg="white", fg="#04286f", font=("Arial", 14, ''))
lblInfoText = Label(self, text="Think carefully when answering and take your time, there is no time limit. The results will be displayed once you have completed the quiz. Any questions you have answered wrong previously will be answered again.", bg="white", fg="#04286f", font=("Arial", 13, ''), wraplength="850")
btnMenu = Button(self, command=MenuButton, text='< Back to Selection', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
btnProceed = Button(self, command=ProceedButton, text='''I'm ready! >''', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
lblHeading.grid(pady=19, columnspan=2, row=0)
lblQuizTitle.grid(columnspan=2, row=1)
lblInfoText.grid(pady=20, columnspan=2, row=2)
btnProceed.grid(column=1, row=3)
btnMenu.grid(column=0, row=3)
class frameQuiz(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")
root.title("Quizzel - %s" % (root.ChosenQuizTitle))
Choice = IntVar()
root.CurrentQuestion = 0
root.Score = 0
A1Stack = []
A2Stack = []
A3Stack = []
A4Stack = []
strQuestionText = StringVar()
strQuestionNo = StringVar()
A1 = StringVar()
A2 = StringVar()
A3 = StringVar()
A4 = StringVar()
CorrectAStack = []
def MenuButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameStudentMenu, parent)
parent.pack(expand=1, fill=BOTH)
def OpenQuiz():
root.QuestionID = []
root.QuestionStack = []
root.WrongQuestion = []
root.WrongAnswer = []
root.CurrentQuestion = 1
root.ShouldSave = False
strQuestionNo.set("Question: 1")
cursor.execute("SELECT QuestionID FROM multichoicequestions WHERE QuizID=?",(root.ChosenQuiz,))
for row in cursor:
root.QuestionID.append(row[0])
root.AllQID = root.QuestionID
cursor.execute("SELECT Question FROM multichoicequestions WHERE QuizID=?",(root.ChosenQuiz,))
for row in cursor:
root.QuestionStack.append(row[0])
cursor.execute("SELECT Answer1 FROM multichoicequestions WHERE QuizID=?",(root.ChosenQuiz,))
for row in cursor:
A1Stack.append(row[0])
cursor.execute("SELECT Answer2 FROM multichoicequestions WHERE QuizID=?",(root.ChosenQuiz,))
for row in cursor:
A2Stack.append(row[0])
cursor.execute("SELECT Answer3 FROM multichoicequestions WHERE QuizID=?",(root.ChosenQuiz,))
for row in cursor:
A3Stack.append(row[0])
cursor.execute("SELECT Answer4 FROM multichoicequestions WHERE QuizID=?",(root.ChosenQuiz,))
for row in cursor:
A4Stack.append(row[0])
cursor.execute("SELECT CorrectAnswer FROM multichoicequestions WHERE QuizID=?",(root.ChosenQuiz,))
for row in cursor:
CorrectAStack.append(row[0])
root.MaxScore = len(root.QuestionStack)
if len(root.QuestionStack) == 1:
btnNext.configure(command=DoneQuiz, text="Finish Quiz >", bg="green")
ShuffleQuiz()
SetLabels()
def SetLabels():
A1.set(A1Stack[len(A1Stack)-1])
A2.set(A2Stack[len(A2Stack)-1])
A3.set(A3Stack[len(A3Stack)-1])
A4.set(A4Stack[len(A4Stack)-1])
strQuestionText.set(root.QuestionStack[len(root.QuestionStack)-1])
def ShuffleQuiz():
combined = list(zip(root.QuestionStack, A1Stack, A2Stack, A3Stack, A4Stack, CorrectAStack, root.QuestionID))
random.shuffle(combined)
root.QuestionStack[:], A1Stack[:], A2Stack[:], A3Stack[:], A4Stack[:], CorrectAStack[:], root.QuestionID[:] = zip(*combined)
def NextQuestion():
C = Choice.get()
rightorwrong = CheckAnswer()
Q = str((root.MaxScore - len(root.QuestionStack)) + 2)
strQuestionNo.set("Question: "+Q)
root.CurrentQuestion = root.CurrentQuestion + 1
if rightorwrong == True:
root.Score = root.Score + 1
for Stack in [A1Stack, A2Stack, A3Stack, A4Stack, root.QuestionStack, CorrectAStack]:
Stack.pop()
if len(root.QuestionStack) == 1:
btnNext.configure(command=DoneQuiz, text="Finish Quiz >", bg="green")
if root.QuestionStack:
strQuestionText.set(str(root.QuestionStack[len(root.QuestionStack)-1]))
A1.set(str(A1Stack[len(A1Stack)-1]))
A2.set(str(A2Stack[len(A2Stack)-1]))
A3.set(str(A3Stack[len(A3Stack)-1]))
A4.set(str(A4Stack[len(A4Stack)-1]))
for A in [btnAnswer1, btnAnswer2, btnAnswer3, btnAnswer4]:
A.deselect()
Choice.set(0)
def DoneQuiz():
rightorwrong = CheckAnswer()
if rightorwrong == True:
root.Score = root.Score + 1
root.ShouldSave = True
self.pack_forget()
parent.pack_forget()
controller.PackFrame(framePostQuiz, parent)
parent.pack(expand=1, fill=BOTH)
def CheckAnswer():
C = Choice.get()
if C == int(CorrectAStack[len(CorrectAStack)-1]):
return True
else:
root.WrongAnswer.append(C)
root.WrongQuestion.append(root.QuestionID[len(root.QuestionID)-1])
root.QuestionID.pop()
return False
lblQuestionNumber = Label(self, textvariable=strQuestionNo, bg="white", fg="#04286f", font=("Arial", 15, 'bold'), wraplength="800")
lblQuestionText = Label(self, textvariable=strQuestionText, bg="white", fg="#04286f", font=("Arial", 15, ''), wraplength="800")
btnAnswer1 = Radiobutton(self, bg="#282828", offrelief=FLAT, wraplength="150", fg="white", activebackground="blue", selectcolor="blue", textvariable=A1, variable=Choice, value=1, indicatoron=0, width=20, height=4)
btnAnswer2 = Radiobutton(self, bg="#282828", offrelief=FLAT, wraplength="150", fg="white", activebackground="blue", selectcolor="blue", textvariable=A2, variable=Choice, value=2, indicatoron=0, width=20, height=4)
btnAnswer3 = Radiobutton(self, bg="#282828", offrelief=FLAT, wraplength="150", fg="white", activebackground="blue", selectcolor="blue", textvariable=A3, variable=Choice, value=3, indicatoron=0, width=20, height=4)
btnAnswer4 = Radiobutton(self, bg="#282828", offrelief=FLAT, wraplength="150", fg="white", activebackground="blue", selectcolor="blue", textvariable=A4, variable=Choice, value=4, indicatoron=0, width=20, height=4)
btnMenu = Button(self, command=MenuButton, text='< Leave Quiz', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
btnNext = Button(self, command=NextQuestion, text='Next Question >', relief=FLAT, bg=root.ButtonColour, fg="white", width='32')
lblQuestionNumber.grid(row=0, columnspan=2)
lblQuestionText.grid(columnspan=2)
btnAnswer1.grid(row=2,column=0,padx=60,pady=30)
btnAnswer2.grid(row=2,column=1,padx=60,pady=30)
btnAnswer3.grid(row=3,column=0,padx=60,pady=30)
btnAnswer4.grid(row=3,column=1,padx=60,pady=30)
btnMenu.grid(column=0, row=4)
btnNext.grid(column=1, row=4)
try:
OpenQuiz()
except:
tkinter.messagebox.showerror("Cannot Open Quiz","This quiz currently has no questions and therefore cannot be opened.")
self.pack_forget()
parent.pack_forget()
frameStudentMenu.pack(self)
parent.pack(expand=1, fill=BOTH)
class framePostQuiz(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")
controller.title("Quizzel - Quiz Completed!")
time_string = time.strftime('%d/%m/%Y, %H:%M')
def MenuButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameStudentMenu, parent)
parent.pack(expand=1, fill=BOTH)
def ReviewButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(frameQuizReview, parent)
parent.pack(expand=1, fill=BOTH)
def SaveResults():
Result = str(root.Score)+'/'+str(root.MaxScore)
cursor.execute('INSERT INTO results(UserID, QuizID, Result, Time) VALUES(?,?,?,?)',(root.UserID,root.ChosenQuiz,Result,time_string))
database.commit()
btnMenu = Button(self, command=MenuButton, text='< Back to Menu', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
btnReview = Button(self, command=ReviewButton, text='Review your answers >', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
lblQuizTitle = Label(self, text="Quiz Completed: %s" % (root.ChosenQuizTitle[0]), bg="white", fg="green", font=("Arial", 15, 'bold'))
lblQuizTitle.grid(pady=19, columnspan=2)
lblScore = Label(self, text="Relax... It's over! You have scored %s out of a total possible %s." % (root.Score, root.MaxScore), bg="white", fg="#04286f", font=("Arial", 14, ''))
lblScore.grid(columnspan=2)
lblInfoText = Label(self, text="The results for this quiz will be saved. Select 'Review' too see where you went wrong feel free to repeat this quiz to improve your score.", bg="white", fg="#04286f", font=("Arial", 13, ''), wraplength="850")
lblInfoText.grid(pady=20, columnspan=2)
if not root.WrongQuestion:
lblScore.configure(text="Amazing! You have scored a perfect %s out of %s!" % (root.Score, root.MaxScore))
lblInfoText.configure(text="The results for this quiz will be saved.")
btnMenu.grid(columnspan=2, row=5)
else:
btnMenu.grid(column=0, row=5)
btnReview.grid(column=1, row=5)
if root.ShouldSave:
SaveResults()
root.ShouldSave = False
class frameQuizReview(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")
controller.title("Quizzel - Review Quiz")
def PostQuizButton():
self.pack_forget()
parent.pack_forget()
controller.PackFrame(framePostQuiz, parent)
parent.pack(expand=1, fill=BOTH)
def ListThings():
r = 5
btnPostQuiz = Button(self, command=PostQuizButton, text='< Back', relief=FLAT, overrelief=SUNKEN, bg=root.ButtonColour, fg="white", activebackground="#04286f", width='32')
Label(self, text="Questions you have answered incorrectly:", bg="white", fg="#04286f", font=("Arial", 14, '')).grid(row=1, pady=19, columnspan=100)
Label(self, text="Question:", bg="white", fg="#04286f", font=("Arial", 12, ''), anchor='w', justify=LEFT).grid(row=2, column=0, sticky='w', pady=20, padx=20)
Label(self, text="Your Answer:", bg="white", fg="#04286f", font=("Arial", 12, ''), anchor='w', justify=LEFT).grid(row=2, column=1, sticky='w', pady=20, padx=20)
for w in root.WrongQuestion:
cursor.execute('''SELECT Question FROM multichoicequestions WHERE QuestionID=?''',(w,))
QText = cursor.fetchone()
r = r + 1
Label(self, text=QText[0], bg="white", fg="#bc0000", font=("Arial", 12, ''), anchor='w', justify=LEFT).grid(row=r, column=0, sticky='w', padx=30)
r = 5
for a, b in zip(root.WrongAnswer, root.WrongQuestion):
if a == 0:
AText = ["No answer"]
else:
a = "Answer" + str(a)
cursor.execute('''SELECT %s FROM multichoicequestions WHERE QuestionID=?''' % (a), (b,))
AText = cursor.fetchone()
r = r + 1
Label(self, text=AText[0], bg="white", fg="#bc0000", font=("Arial", 12, ''), anchor='e', justify=RIGHT).grid(row=r, column=1, sticky='e', padx=20)
r = r + 1
btnPostQuiz.grid(row=r, columnspan=100, pady=19)
ListThings()
class framePasswordChange(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg="white")