-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEveUI.py
4049 lines (3622 loc) · 164 KB
/
EveUI.py
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
MYSQL = "mysql"
MICROSOFTSQL = "mssql"
##############################################################################################
#############################CHANGE SERVER DETAILS HERE !!!!!!!!!!!!!#########################
#VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV#
SERVERADDRESS="evoice.cermmtd1vgvf.eu-west-2.rds.amazonaws.com"
PORT=3306
USERNAME="eVoice"
PASSWORD="latymerevoice"
DATABASE="evoice"
SERVERARCHITECTURE = MYSQL #Change this from MYSQL to MICROSOFTSQL depending on what the server is running
##############################################################################################
#Imports
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.filedialog
from PIL import ImageTk ,Image
from tkcalendar import Calendar, DateEntry
import random
import time
import mysql.connector
import pyodbc
import xlsxwriter
from datetime import date
from datetime import datetime
import os
import os.path
import copy
import requests
import ctypes
import sys
import pickle
import glob
##############Global variables
#Login page
backgroundLabel = None #Background label window
loginFrame = None #Login window
loginButton = None #Login button
usernameEntry = None #The username entry box
passwordEntry = None #The password entry box
#Login details
userName = '' #Username
passWord = '' #Password
#Form
toDoArea = None #Do do surveys window
missingArea = None #Missing surveys window
formFrame = None #Window for the forms
classID = None #Class ID (unique based on form)
questionFrame = None #The window for answering questions
people = None #Number of people in a class
#Answering surveys
addRowButtons = {} #List of buttons to add answer rows
removeRowButtons = {} #List of buttons to remove answer rows
surveyArea = None #The window in which a survey is taken
classNameMap = {} #The map of classIDs to class names (for efficiency)
firstTimeClassName = True #Variable storing whether the class name map has been populated
surveyTitle = None #The title of the survey
#School council
schoolCouncilFrame = None #School councillor window
accessLevel = None #The access level of a councillor
createNewAccountsArea = None #The create new account window
statisticsArea = None #The window in which survey stats are displayed
passArea = None #The area a new password is entered
userdatalabels = [] #List of users searched for
#Creating surveys
firstAddButton = None #The handle to the first question add button
incorrectSurveyLabel = None #The label displaying an error in survey creation
createNewSurveyArea = None #The create new survey window
questionEntries = [] #List of boxes in which to enter questions
#New users
newPass = '' #The new password
newPassEntry = None #The new password entry box
newUserSurnameEntryBox = None #The new surname entry box
newUserFirstnameEntryBox = None #The new first name entry box
newUserUsernameEntryBox = None #The new username entry box
newUserPasswordEntryBox = None #The new password entry box
setAccessLevelEntry = None #Entry drop down to choose access level
newUserSurnameEntry = '' # The entry data into the newSurname box
newUserFirstnameEntry = '' #The entry data into the newFirstname box
newUserUsernameEntry = '' #The entry data into the newUsername box
newUserPasswordEntry = '' #The entry data into the newPassword box
newAccessLevel = '' #The entry data into the new accessLevel box
#Deleting users
toDeleteUsernameEntry = None #The entry box for the username to delete
toDeleteUsername = '' #The username to delete
#Offline surveys
offline = False #Whether the user is offline
offlineSurvey = None #The handle to the offline survey
offlinePeople = 0 #The number of people offline
offlineclass= None #The class name when offline
#Misc
save = None #Save function
popupWin =None #A pop up window global handle
allClassesList = [] #A list of all classes
###########Constants
VERSION = 4 #Program version
TWOSAME = "¬||¬||¬||¬" #Constant that can be returned (Akin to false, prevents autotyping issues)
QUESTIONTYPEOPTIONS = 0 #Options question
QUESTIONTYPEOPEN = 1 #Open question
ID_QUESTIONTYPE = 2 #Question type array index
ID_QUESTIONID = 0 #Question ID array index
ID_QUESTIONBODY = 1 #Question Body array index
ID_SURVEYOR = 0 #Surveyor type
ID_CLASS = 1 #Class type
ID_CLASS_NEW = 2 #New class type
ACCESSLEVELR = 0 #Read permissions - view surveys and download
ACCESSLEVELRW = 1 #Write permissions - add new and alter old surveys/questions
ACCESSLEVELA = 2 #Add and remove councillor users, classes - administrator
ACCESSLEVELS = 3 #Add and remove administrators - system
ACCESSLEVELP = 4 #Program access level - program uses to automatically add and delete users
#return relative_path
def resourcePath(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
###########################QUESTION CLASSES
#A question - takes all the parameters stored in the DB
class Question:
def __init__(self, questionID, surveyID, questionType, questionBody, questionNumber, targetYears):
self.questionID = questionID
self.surveyID = surveyID
self.questionType = questionType
self.questionBody = questionBody
self.questionNumber = questionNumber
self.targetYears = targetYears
#An answer - takes all the parameters stored in the DB
class Answer:
def __init__(self, className, questionID, answerType, answerList, complete):
self.className = className
self.questionID = questionID
self.answerType = answerType
self.answerList = answerList
self.complete = complete
#A full survey - consists of a list of questions, answers and survey information
class Survey:
def __init__(self, surveyID, name, questionIDs, people = None):
self.questionIDs = questionIDs
self.name = name
self.surveyID = surveyID
self.questions = []
self.answers = []
self.classID = None
self.people = people
#Fetch the information from the server
def getInformation(self):
for questionID in self.questionIDs:
sql = "Select * from Question where questionID = " + str(questionID)
csr.execute(sql)
qd = csr.fetchall()[0]
q = Question(qd[0],qd[1],qd[2],qd[3],qd[4], targetYearsParse(qd[5]))
self.questions.append(q)
#Submit infomation to the server
def setInformation(self):
classID = getClassID(self.answers[0].className)
if getClassPeople(classID) == -1:
self.people = 30
changeClassPeople(classID, self.people, ACCESSLEVELP)
for answer in self.answers:
if answer.complete == 1:
submitAnswer(answer.answerList, answer.questionID, classID, answer.answerType, offlineAnswer = True)
#Gets a list of questions to do
def getQuestions(self):
global offlineclass
outQuestions = []
for question in self.questions:
if getYear(name = offlineclass) in question.targetYears:
inAnswer = False
for answer in self.answers:
if answer.questionID == question.questionID :
if answer.complete == 0:
outQuestions.append(question)
break
inAnswer = True
if not inAnswer:
outQuestions.append(question)
return outQuestions
#A scrollable frame - take the width, height and background colour, along with the parent (container)
#width and height aren't needed if pack is used to display
#You should pack the ScrollableFrame object itself
#But the parent window for children should be the scrollable frame (ScrollableFrane.scrollableFrame)
class ScrollableFrame(tk.Frame):
def __init__(self, container, verticalSB = True, horizontalSB = False, height= -1, width=-1, *args, **kwargs):
"""Pass in height, width and background colour"""
super().__init__(container, *args, **kwargs)
if verticalSB and horizontalSB:
raise ValueError("Cannot have more than one scrollbar in a window.\n Please put horizontal Scrollable frame IN vertical one")
if height == -1 and width == -1:
self.canvas = tk.Canvas(self,highlightthickness=0)
else:
self.canvas = tk.Canvas(self, height = height, width = width, highlightthickness=0)
if verticalSB:
vscrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
if horizontalSB:
hscrollbar = ttk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
self.scrollableFrame = tk.Frame(self.canvas)
self.scrollableFrame.bind(
"<Configure>",
lambda e: self.canvas.configure(
scrollregion=self.canvas.bbox("all")
)
)
self.canvas_frame = self.canvas.create_window((0, 0), window=self.scrollableFrame, anchor="nw")
if verticalSB:
self.canvas.configure(yscrollcommand=vscrollbar.set)
if horizontalSB:
self.canvas.configure(xscrollcommand=hscrollbar.set)
if verticalSB:
vscrollbar.pack(side="right", fill="y")
self.canvas.pack(side="left", fill="both", expand=True, anchor = 'nw')
if horizontalSB:
hscrollbar.pack(side="bottom", fill="x")
self.canvas.pack(side="top", fill="both", expand=True, anchor = 'nw')
self.canvas.bind('<Configure>', self.FrameWidth)
def FrameWidth(self, event):
canvas_width = event.width
self.canvas.itemconfig(self.canvas_frame, width = canvas_width)
#A Popup window with some text and if an entry box should be displayed
class PopupWindow(object):
def __init__(self, parent, text, entryBoxNeeded = True):
top=self.top=tk.Toplevel(parent)
self.entryBoxNeeded = entryBoxNeeded
#Add the icon
try:
icon = ImageTk.PhotoImage(Image.open(resourcePath("icon.png")))
icon.image = resourcePath("icon.png")
self.top.iconphoto(False, icon)
except:
pass
self.l=tk.Label(top,text=text)
self.l.bind('<Configure>', lambda e: self.l.config(wraplength=self.l.winfo_width()))
self.l.pack(fill="both", expand =True)
if self.entryBoxNeeded: #Only creates entry if requested
self.e=tk.Entry(top)
self.e.pack()
self.b=tk.Button(top, text='Ok', command=self.cleanup, width = 30) #Button destroys window
self.b.pack()
#Destroys itself when button is pressed
def cleanup(self):
if self.entryBoxNeeded:
self.value=self.e.get()
self.top.destroy()
#Class for entering a new question (school council) - the startColumn and rows are passed in as well as question details and the parent window
class QuestionEntry():
def __init__(self, parent, startColumn, addRows, position, options = [], questionType = -1, questionBody = "", targetYears = []):
###Set local variables and constants
#Columns and rows for windows
self.QUESTIONENTRYCOLUMN = 1
self.QUESTIONLABELCOLUMN = 0
self.QUESTIONTYPECOLUMN = 2
self.TARGETYEARSCOLUMN = 2
self.ENTRYBOXENTRYCOLUMN = 1
self.ENTRYBOXLABELSCOLUMN = 0
self.ADDCOLUMN = 0
self.REMOVECOLUMN = 3
#Variables
self.addRows = addRows
self.startRow = (position * 100) + addRows
self.position = position
self.startColumn = startColumn
self.parent = parent
self.options = []
self.options = options
self.optionsBoxes = []
self.optionsLabels = []
###Create boxes and menus
count = 1
#Option boxes
for option in self.options:
self.optionsBoxes.append(tk.Entry(self.parent, font = ('verdana', 12), relief = tk.RIDGE))
self.optionsBoxes[len(self.optionsBoxes) -1 ].insert(0, option)
self.optionsLabels.append(tk.Label(self.parent, text = "Option " + str(count) + ":", font = ('verdana', 12)))
count += 1
#Drop box
self.dropBox = ttk.Combobox(
parent,
width = 27,
values= [
'<Choose a question type>',
'Multi-optioned',
'Open Ended',
'Yes/No',
],
state = "readonly"
)
self.dropBox.bind("<<ComboboxSelected>>", lambda e: self.display())
self.dropBox.current(int(questionType)+1)
#Target year checkboxes
self.checkBoxes = [[],[]]
self.years = [7, 8, 9, 10, 11, 12, 13]
for year in self.years:
if year in targetYears:
self.checkBoxes[1].append(tk.IntVar(value = 1))
else:
self.checkBoxes[1].append(tk.IntVar())
self.checkBoxes[0].append(tk.Checkbutton(self.parent, text = int(year),
variable = self.checkBoxes[1][len(self.checkBoxes[1]) - 1],
onvalue = 1,
offvalue = 0,
height = 2,
width = 10))
self.targetYearsLabel = ttk.Label(self.parent, text='Select years to set to', font = ('verdana', 12))
#Questions
self.questionTitleLabel = ttk.Label(self.parent, text='Question ' + str(self.position) + ":", font = ('verdana', 18))
self.questionTitleEntry = tk.Entry(self.parent, font = ('verdana', 12), relief = tk.RIDGE)
self.questionTitleEntry.insert(0, questionBody)
self.add = tk.Button(
parent,
bd = 0,
activeforeground = '#4d84af',
bg = '#2f2f31',
fg = 'white',
activebackground = '#2f2f31',
text = 'Add Question',
font = ('verdana', 12),
)
self.remove = tk.Button(
parent,
bd = 0,
activeforeground = '#4d84af',
bg = '#2f2f31',
fg = 'white',
activebackground = '#2f2f31',
text = 'Remove Question',
font = ('verdana', 12),
)
#Destroys the question structure and returns the startRow of the object
def destroy(self):
for ob in self.optionsBoxes:
try:
ob.destroy()
except:
pass
for ol in self.optionsLabels:
try:
ol.destroy()
except:
pass
for cb in self.checkBoxes[0]:
try:
cb.destroy()
except:
pass
try:
self.questionTitleLabel.destroy()
except:
pass
try:
self.questionTitleEntry.destroy()
except:
pass
try:
self.dropBox.destroy()
except:
pass
try:
self.add.destroy()
except:
pass
try:
self.remove.destroy()
except:
pass
try:
self.addEntry.destroy()
except:
pass
try:
self.removeEntry.destroy()
except:
pass
try:
self.targetYearsLabel.destroy()
except:
pass
return self.startRow
#Moves the question up in the question order
def moveUp(self):
self.position = self.position - 1
self.startRow = (self.position * 100) + self.addRows
self.display()
#Moves the question down in the question order
def moveDown(self):
self.position = self.position + 1
self.startRow = (self.position * 100) + self.addRows
self.display()
#Displays the object by gridding all the Tk objects
def display(self):
#Remove all the Tk objects
for ob in self.optionsBoxes:
try:
ob.grid_forget()
except:
pass
for ol in self.optionsLabels:
try:
ol.grid_forget()
except:
pass
for cb in self.checkBoxes[0]:
try:
cb.grid_forget()
except:
pass
try:
self.questionTitleLabel.grid_forget()
except:
pass
try:
self.questionTitleEntry.grid_forget()
except:
pass
try:
self.dropBox.grid_forget()
except:
pass
try:
self.add.grid_forget()
except:
pass
try:
self.remove.grid_forget()
except:
pass
try:
self.addEntry.destroy()
except:
pass
try:
self.removeEntry.destroy()
except:
pass
try:
self.targetYearsLabel.grid_forget()
except:
pass
#Redraw all the windows
questionType = self.dropBox.current() - 1
if questionType == 2:
self.displayTargetYears()
elif questionType == QUESTIONTYPEOPTIONS:
self.displayTargetYears()
self.displayOptionsEntry()
elif questionType == QUESTIONTYPEOPEN:
self.displayTargetYears()
self.questionTitleLabel.config(text='Question ' + str(self.position) + ":")
self.questionTitleLabel.grid(row = self.startRow, column = self.QUESTIONLABELCOLUMN, padx = 20, pady = 20)
self.questionTitleEntry.grid(row = self.startRow, column = self.QUESTIONENTRYCOLUMN, padx = 20, pady = 20)
self.dropBox.grid(row = self.startRow, column = self.QUESTIONTYPECOLUMN, padx = 20, pady = 20)
if len(self.optionsLabels) > len(self.years):
self.add.grid(row = self.startRow + len(self.optionsLabels) + 1, column = self.ADDCOLUMN, padx = 20, pady = 20)
else:
self.add.grid(row = self.startRow + len(self.years) + 2, column = self.ADDCOLUMN, padx = 20, pady = 20)
self.remove.grid(row = self.startRow, column = self.REMOVECOLUMN, padx = 20, pady = 20)
#Displays target year checkboxes
def displayTargetYears(self):
row = self.startRow + 2
self.targetYearsLabel.grid(row = self.startRow + 1, column = self.TARGETYEARSCOLUMN, padx = 20, pady = 20)
for checkBox in self.checkBoxes[0]:
checkBox.grid(row=row, column = self.TARGETYEARSCOLUMN)
row += 1
#Removes a single row for options entry
def removeEntryRow(self):
self.optionsBoxes[len(self.optionsBoxes)-1].destroy()
self.optionsBoxes.pop(len(self.optionsBoxes)-1)
self.optionsLabels[len(self.optionsLabels)-1].destroy()
self.optionsLabels.pop(len(self.optionsLabels)-1)
self.displayOptionsEntry()
#Adds a single row for options entry
def addEntryRow(self):
labelNumber = len(self.optionsBoxes) + 1
self.optionsBoxes.append(tk.Entry(self.parent, font = ('verdana', 12), relief = tk.RIDGE))
self.optionsLabels.append(tk.Label(self.parent, text = "Option " + str(labelNumber) + ":", font = ('verdana', 12)))
self.displayOptionsEntry()
#Displays the options entry boxes
def displayOptionsEntry(self):
currentInternalRow = self.startRow + 1
#Must destroy all current boxes first to avoid overlapping
try:
self.addEntry.destroy()
except:
pass
try:
self.removeEntry.destroy()
except:
pass
for box in self.optionsBoxes:
try:
box.grid_forget()
except:
pass
for label in self.optionsLabels:
try:
label.grid_forget()
except:
pass
#Redraw all windows
for i in range(len(self.optionsBoxes)):
self.optionsBoxes[i].grid(row = currentInternalRow, column = self.ENTRYBOXENTRYCOLUMN, padx = 20, pady = 20)
self.optionsLabels[i].grid(row = currentInternalRow, column = self.ENTRYBOXLABELSCOLUMN, padx = 20, pady = 20)
currentInternalRow += 1
self.addEntry = tk.Button(
self.parent,
bd = 0,
activeforeground = '#4d84af',
bg = '#2f2f31',
fg = 'white',
activebackground = '#2f2f31',
text = 'Add Option',
font = ('verdana', 12),
command = lambda :self.addEntryRow()
)
self.removeEntry = tk.Button(
self.parent,
bd = 0,
activeforeground = '#4d84af',
bg = '#2f2f31',
fg = 'white',
activebackground = '#2f2f31',
text = 'Remove Option',
font = ('verdana', 12),
command = lambda: self.removeEntryRow()
)
self.addEntry.grid(row = currentInternalRow, column = self.ENTRYBOXLABELSCOLUMN, padx = 20, pady = 20)
if len(self.optionsBoxes) > 0:
self.removeEntry.grid(row =currentInternalRow, column = self.ENTRYBOXENTRYCOLUMN, padx = 20, pady = 20)
self.add.grid_forget()
if len(self.optionsLabels) > len(self.years):
self.add.grid(row = currentInternalRow + 1, column = self.ADDCOLUMN, padx = 20, pady = 20)
else:
self.add.grid(row = self.startRow + len(self.years) + 2, column = self.ADDCOLUMN, padx = 20, pady = 20)
#Gets the data from each of the boxes, compiles it and outputs the 6 required pieces of information
#If an error occurs, False and the error code are returned as well as 4 None variables which are not used
def getData(self):
questionType = self.dropBox.current() - 1
options = []
question = ""
if questionType == -1:
return False, "No question type selected", None, None, None, None
if questionType == QUESTIONTYPEOPTIONS:
for ob in self.optionsBoxes:
option = ob.get()
if option != "":
options.append(option)
if len(options) < 1:
return False, "Not enough options supplied", None, None, None, None
question = self.questionTitleEntry.get()
if question == "":
return False, "Question title not input", None, None, None, None
targetYears = []
for i in range(len(self.checkBoxes[1])):
if self.checkBoxes[1][i].get() == 1:
targetYears.append(i + 7)
targetYears.sort()
if len(targetYears) == 0:
return False, "Target years not selected", None, None, None, None
return True, "Success", question, questionType, targetYears, options
if questionType == QUESTIONTYPEOPEN:
options = None
question = self.questionTitleEntry.get()
if question == "":
return False, "Title not input", None, None, None, None
targetYears = []
for i in range(len(self.checkBoxes[1])):
if self.checkBoxes[1][i].get() == 1:
targetYears.append(i + 7)
targetYears.sort()
if len(targetYears) == 0:
return False, "Target years not selected", None, None, None, None
if questionType == 2:
options = ["Yes", "No"]
questionType = QUESTIONTYPEOPTIONS
question = self.questionTitleEntry.get()
if question == "":
return False, "Title not input", None, None, None, None
targetYears = []
for i in range(len(self.checkBoxes[1])):
if self.checkBoxes[1][i].get() == 1:
targetYears.append(i + 7)
targetYears.sort()
if len(targetYears) == 0:
return False, "Target years not selected", None, None, None, None
return True, "Success", question, questionType, targetYears, options
#######################################################################################################
################################################ UI ###################################################
#######################################################################################################
#Starts the User interface
def start():
"""The main UI function"""
startUI = tk.Tk()
startUI.state('zoomed')
startUI.configure(bg='#6f6f6f')
startUI.title('Eve')
try:
icon = ImageTk.PhotoImage(Image.open(resourcePath("icon.png")))
icon.image = resourcePath("icon.png")
startUI.iconphoto(False, icon)
except:
pass
startUI.minsize(900, 450)
#Displays the program information (F1)
def progInfo():
"""Program Info"""
text = ("E-voice (Eve) Survey Viewer Version 1.3\n "
"© Copyright 2020\n"
"Jacqueline Dobreva, Isaac Skevington\n"
"All Rights Reserved\n"
"You are not licensed to copy, change, or distribute this software without permission, for profit or otherwise\n"
"Doing so could leave you open to suit\n"
"Report any issues to [email protected] or [email protected]\n"
"This program contains: 4050 line of code, Stable Build 23:36, 16/11/2020\n\n"
"Changes from 1.2:\n"
"Offline mode added, bugs fixed")
PopupWindow(startUI, text, entryBoxNeeded=False)
#A little easter egg :)
def easterEggI():
"""Isaac's Easter egg :)"""
text = "Hot cross bun time ~ I\n"
PopupWindow(startUI, text, entryBoxNeeded=False)
#Binding Keys to above functions
startUI.bind('<F1>', lambda e : progInfo())
startUI.bind('<F8>', lambda e : easterEggI())
global save
#Opens an offline survey file
def openFile():
filename = tk.filedialog.askopenfilename(title = "Open survey", defaultextension = ".evs", filetypes = [("Survey Files", ".evs")])
return filename
#Returns a user selected filename (default is xlsx extension, but also used for the Survey files)
def saveFile(filename, defaultextension = ".xlsx", filetypes = [("Excel Spreadsheet",".xlsx")]):
startUI.filename = tk.filedialog.asksaveasfilename(initialdir = "/",
title = "Save As",
filetypes = filetypes,
defaultextension= defaultextension,
initialfile = filename)
return startUI.filename
save = saveFile
def incorrect():
"""Incorrect login alert"""
global backgroundLabel
incorrectLabel = tk.Label(
startUI,
fg = 'red',
bg = '#ffffff',
text = 'Incorrect username / password',
wraplength = 100,
justify="center"
)
incorrectLabel.bind('<Configure>', lambda e: incorrectLabel.config(wraplength=incorrectLabel.winfo_width()))
incorrectLabel.place(relx = 0.6, rely = 0.590, relwidth = 0.1)
startUI.mainloop()
def levelOfAccess():
"""Returns access level, asks for class numbers, or calls incorrect function"""
global userName
global passWord
global classID
global usernameEntry
global passwordEntry
global accessLevel
global offlineSurvey
global offline
global offlinePeople
global offlineclass
usernameEntry = userName.get()
passwordEntry = passWord.get()
if offline: #If the user is offline
surveyFile = openFile()
offlinePeople = enterClassPeoplePopUp()
with open (surveyFile, 'rb') as file:
offlineSurvey = pickle.load(file)
offlineSurvey.people = offlinePeople
offlineclass = usernameEntry
form(None)
else: #Otherwise try to log the user in
loginSuccess, userType, userData = sqlLogin(usernameEntry, passwordEntry)
#Handle the login
if loginSuccess:
if userType == ID_SURVEYOR:
accessLevel = userData
schoolCouncil(accessLevel)
else:
if userType == ID_CLASS_NEW:
people = enterClassPeoplePopUp()
changeClassPeople(userData, people, ACCESSLEVELP)
classID = userData
form(classID)
else:
incorrect()
def enterClassPeoplePopUp():
"""Prompts new class to enter total number of students"""
global popupWin
global loginButton
popupWin=PopupWindow(startUI, "You haven't logged in before, please\n enter the number of people in your class")
loginButton["state"] = "disabled"
startUI.wait_window(popupWin.top)
loginButton["state"] = "normal"
return popupWin.value
def schoolCouncil(access):
"""Main school council function, 1 of 2 possible pages post login"""
global backgroundLabel
global loginFrame
global surveyArea
global createNewAccountsArea
global statisticsArea
global schoolCouncilFrame
global createButton
#Destroys superfluous frames
try:
schoolCouncilFrame.destroy()
except:
pass
try:
backgroundLabel.destroy()
except:
pass
try:
loginFrame.destroy()
except:
pass
schoolCouncilFrame = tk.Frame(startUI, bd = 0)
schoolCouncilFrame.pack(expand = tk.YES, fill = tk.BOTH, anchor = 'nw', side = "top")
sidebar = tk.Frame(schoolCouncilFrame, width = 220, bg = '#2f2f31')
sidebar.pack(expand = 0, fill = tk.BOTH, side = 'left', anchor = 'nw')
def changeToNewPass():
"""Enforces changes of user pass to new pass (UI)"""
global newPass
global newPassEntry
global usernameEntry
global passwordEntry
newPass = newPassEntry.get()
changePassword(usernameEntry, passwordEntry, newPass)
schoolCouncil(accessLevel)
def changePass():
"""Follows 'change password' button click"""
global surveyArea
global statisticsArea
global createNewAccountsArea
global classID
global passArea
global newPassEntry
global createNewSurveyArea
#Destroys superfluous frames
try:
createNewSurveyArea.destroy()
except:
pass
try:
surveyArea.destroy()
except:
pass
try:
statisticsArea.destroy()
except:
pass
try:
createNewAccountsArea.destroy()
except:
pass
try:
questionFrame.destroy()
except:
pass
try:
passArea.destroy()
except:
pass
try:
createButton.destroy()
except:
pass
try:
incorrectSurveyLabel.destroy()
except:
pass
passArea = ScrollableFrame(schoolCouncilFrame, width = 800)
parent = passArea.scrollableFrame
parent.grid_rowconfigure(0, weight=1)
parent.grid_columnconfigure(0, minsize=80)
parent.grid_columnconfigure(1, minsize=80)
parent.grid_rowconfigure(2, minsize=80)
parent.grid_rowconfigure(1, minsize=80)
#Attached to entry widgets- allows 'fade in, fade out' effect of text
def on_entry_click(event):
if newPassEntry.cget('fg') == 'grey':
newPassEntry.delete(0, "end")
newPassEntry.insert(0, '')
newPassEntry.config(fg = 'black', show = '•')
def on_focusout(event):
if newPassEntry.get() == '':
newPassEntry.insert(0, 'New Password')
newPassEntry.config(fg = 'grey', show = '')
#user entry space for new password
newPassEntry = tk.Entry(parent, font = ('verdana', 12), relief = tk.RIDGE,)
newPassEntry.insert(0, 'New Password')
newPassEntry.bind('<FocusIn>', on_entry_click)
newPassEntry.bind('<FocusOut>', on_focusout)
newPassEntry.config(fg = 'grey')
newPassEntry.grid(column = 0, row = 1, sticky = 'NSEW', padx = (30, 30), pady = (50, 50))
changeButton = tk.Button(
parent,
bd = 0,
activeforeground = '#4d84af',
bg = '#2f2f31',
fg = 'white',
activebackground = '#2f2f31',
text = 'Change',
anchor = tk.W,
font = ('verdana', 12),
width = '15',
padx = 10,
pady = 10,
command = changeToNewPass
)
changeButton.grid(column = 1, row = 1, sticky = 'nsew', padx = (30, 30), pady = (50, 50))
warningLabel = tk.Label(parent, font = ('verdana', 18, "underline", "bold"), text = "Use a different password to other sites!")
warningLabel.grid(column = 0, row = 0, padx = 30, pady = 10, columnspan = 3)
#Changes buttons to make sure active/inactive appearance is maintained, even after immediate click
statisticsButton.config(fg = 'white', bg = '#2f2f31', text = '« Survey Statistics')
surveysButton.config(fg = 'white', bg = '#2f2f31', text = '« Existing Surveys')
createNewAccountsButton.config(fg = 'white', bg = '#2f2f31', text = '« Create/Delete\nAccounts')
createNewSurveyButton.config(fg = 'white', bg = '#2f2f31', text = '« Create New \nSurvey')
passArea.pack(expand = True, fill = "both")
startUI.mainloop()
def createNAButtonFunc():
"""Function called by clicking button to create a new account"""
global newUserSurnameEntryBox
global newUserFirstnameEntryBox
global newUserUsernameEntry
global newUserPasswordEntry
global setAccessLevelEntry
global newUserSurnameEntry
global newUserFirstnameEntry
global newUserUsernameEntryBox
global newUserPasswordEntryBox
global newAccessLevel
global accessLevel
global createNewAccountsArea
#Creating an account Entry boxes
newUserSurnameEntry = newUserSurnameEntryBox.get()
newUserFirstnameEntry = newUserFirstnameEntryBox.get()
newUserUsernameEntry = newUserUsernameEntryBox.get()
newUserPasswordEntry = newUserPasswordEntryBox.get()
if newUserUsernameEntry == "Username" or newUserPasswordEntry == "Password" or newUserFirstnameEntry == "First name" or newUserSurnameEntryBox == "Surname":
newAccessLevel = 100
if newUserUsernameEntry == "" or newUserPasswordEntry == "" or newUserFirstnameEntry == "" or newUserSurnameEntryBox == "":
newAccessLevel = 100
newAccessLevel = setAccessLevelEntry.current() - 1
if newAccessLevel < 0:
newAccessLevel = 100
if not createSurveyor(newUserUsernameEntry, newUserPasswordEntry, newAccessLevel, accessLevel, firstname = newUserFirstnameEntry, surname = newUserSurnameEntry):
noCanDo = tk.Label(
createNewAccountsArea.scrollableFrame,
fg = 'red',
bg = 'white',
font = ('verdana', 12),
text = 'Incorrect Details'
)
noCanDo.grid(column = 1, row = 1, sticky = 'NSEW', columnspan = 4)
else:
schoolCouncil(accessLevel)
def deleteThisUser():
"""Deletes existing user (UI side)"""
global toDeleteUsernameEntry
global toDeleteUsername
toDeleteUsername = toDeleteUsernameEntry.get()
if deleteSurveyorAccount(toDeleteUsername, access):
schoolCouncil(access)
def createNewAccounts():
"""UI for creating new accounts of deleting exsisting ones"""
global surveyArea
global statisticsArea
global createNewAccountsArea
global createButton
global classID
global passArea
global newUserSurnameEntryBox
global newUserFirstnameEntryBox
global newUserUsernameEntryBox
global newUserPasswordEntryBox
global setAccessLevelEntry
global toDeleteUsernameEntry