Repository navigation
Expand file tree
/
Copy pathGUI_Integration.py
More file actions
2027 lines (1496 loc) · 70.4 KB
/
Copy pathGUI_Integration.py
File metadata and controls
2027 lines (1496 loc) · 70.4 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
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
import tkinter as tk
import numpy as np
from tkinter import ttk
from tkinter import N,S,E,W, NO, YES, END, FIRST, LAST, DISABLED, NORMAL, TOP, BOTTOM, LEFT, RIGHT
import sys
from PIL import Image,ImageTk
import time, datetime
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk, FigureCanvasTk
from matplotlib.figure import Figure
from matplotlib import style
import matplotlib.animation as animation
import matplotlib.dates as mdates
from dbinterface.DBGUIAPI import DBManager
from src.Stats_gen.Data_preprocessing import format_attempts as dataframe
from src.Stats_gen.Stats_Generator import display_dataframe, error_rate, fail_success
from src.Stats_gen.Stats_Generator import *
from dbinterface.DBAlgoAPI import KeyCodeTools
import pandas as pd
global subjectList, topicList
subjectList = DBManager().get_all_subjects_list()
topicList = DBManager().get_all_subject_topics_dict()
LARGE_FONT = ("Verdana", 12)
MEDIUM_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)
Large_Bold_Font = ("Verdana", 12, 'bold')
Medium_Bold_Font = ("Verdana", 10, 'bold')
F = Figure(figsize=(5, 6), dpi=100)
F.subplots_adjust(left=0.1, right=0.95, bottom=0.15, top=0.92)
Add = F.add_subplot(111)
style.use("ggplot")
def NavButtons(frame, parent, controller, text):
"""
Function to create the buttons to navigate between pages
:param frame: Frame in which the buttons are placed
:param parent: parent frame
:param controller: tk.Tk defined in base class
:param text: Header title
:return: None
"""
tk.Frame.__init__(frame, parent)
MainFrame = tk.Frame(frame)
HeaderFrame = tk.Frame(MainFrame)
ButtonFrame = tk.Frame(MainFrame)
label = ttk.Label(HeaderFrame, text=text, font=LARGE_FONT)
label.grid(row=0, column=0, padx=10, pady=10, sticky=N+S+E+W)
home_button = ttk.Button(ButtonFrame, text="Home Page",
command=lambda: controller.switch_page(StartPage))
home_button.grid(row=0, column=0, padx=10, pady=10, sticky=N+S+E+W)
class_button = ttk.Button(ButtonFrame, text="Class Overview",
command=lambda: controller.switch_page(ClassesPage))
class_button.grid(row=0, column=1, padx=10, pady=10, sticky=N+S+E+W)
exam_button = ttk.Button(ButtonFrame, text="Exams",
command=lambda: controller.switch_page(ExamPage))
exam_button.grid(row=0, column=2, padx=10, pady=10, sticky=N+S+E+W)
stats_button = ttk.Button(ButtonFrame, text="Statistics",
command=lambda: controller.switch_page(StatsPage))
stats_button.grid(row=0, column=3, padx=10, pady=10, sticky=N+S+E+W)
HeaderFrame.grid(row=0, column=0, sticky=N+S+E+W)
ButtonFrame.grid(row=1, column=0, sticky=N+S+E+W)
MainFrame.grid(row=0, column=0, sticky=N+S+E+W)
def Input_Parser(string, direction='u2d'):
"""
Function to change database nomenclature to user interface and vice versa
:param string: string to convert
:param direction: 'd2u' --> Database to User ; 'u2d' --> User to Database
:return: formatted string
"""
if direction.lower() == 'u2d':
out = string.replace(" ","_")
elif direction.lower() == 'd2u':
out = string.replace("_"," ")
else:
raise TypeError
return out
def TreeView(frame, version='full', **kwargs):
"""
Function to create subject Treeviews
:param frame: Frame in which to place the treeview
:param version: if full, it gets all available items, if not, it gets a certain set of items
:param kwargs: -
:return: Treeview and scrollbar objects
"""
style = ttk.Style()
style.configure('Treeview', rowheight=30)
scrollbar = tk.Scrollbar(frame)
if version.lower() == 'full':
tree = ttk.Treeview(frame, yscrollcommand=scrollbar.set, height=30)
scrollbar.config(command=tree.yview_scroll)
sub_values = []
top_values = {}
for i, subject in enumerate(subjectList):
sub_t_amount = len(topicList[subject])
sub_q_amount = 0
sub_q_done = 0
top_values[subject] = []
for topic in topicList[subject]:
df1, df2 = dataframe(KeyCodeTools().get_all_keycodes(topic))
count_failure, count_success, ratio = basic_stats(df1)
top_q_amount = KeyCodeTools().get_question_amount(topic)
top_q_done = count_failure + count_success
sub_q_amount += top_q_amount
sub_q_done += top_q_done
top_values[subject].append((' ', top_q_amount, top_q_done))
sub_values.append((sub_t_amount, sub_q_amount, sub_q_done))
namelst = ["Name", "# Topics", "# Questions", "# Questions Done"]
widthlst = [250, 150, 150, 200]
tree["columns"] = ["#{0}".format(i) for i in range(1, len(namelst))]
for i in range(len(tree["columns"])+1):
tree.column(f"#{i}", width=widthlst[i], minwidth=widthlst[i])
tree.heading(f"#{i}", text=namelst[i])
Levels = {}
i = 1
for idx_1, subject in enumerate(subjectList):
subject_u = Input_Parser(subject, 'd2u')
j = 1
Levels[subject] = tree.insert("", 'end', iid="{0}.{1}".format(i, 0), text=subject_u,
values=sub_values[idx_1])
for idx_2, topic in enumerate(topicList[subject]):
topic_u = Input_Parser(topic, 'd2u')
tree.insert(Levels[subject], 'end', iid="{0}.{1}".format(i, j), text=topic_u, values=top_values[subject][idx_2])
j += 1
i += 1
else:
tree = ttk.Treeview(frame, yscrollcommand=scrollbar.set, height=14)
scrollbar.config(command=tree.yview_scroll)
sub_values = []
top_values = {}
for i, subject in enumerate(subjectList):
sub_q_done = 0
top_values[subject] = []
for topic in topicList[subject]:
df1, df2 = dataframe(KeyCodeTools().get_all_keycodes(topic))
count_failure, count_success, ratio = basic_stats(df1)
top_q_done = count_failure + count_success
sub_q_done += top_q_done
top_values[subject].append((top_q_done, 0))
sub_values.append((sub_q_done, 0))
namelst = ["Name", "# Questions Done", "Score"]
widthlst = [200, 110, 80]
tree["columns"] = ["#{0}".format(i) for i in range(1, len(namelst))]
for i in range(len(tree["columns"])+1):
tree.column(f"#{i}", width=widthlst[i], minwidth=widthlst[i])
tree.heading(f"#{i}", text=namelst[i])
Levels = {}
i = 1
for idx_1, subject in enumerate(subjectList):
subject_u = Input_Parser(subject, 'd2u')
j = 1
Levels[subject] = tree.insert("", 'end', iid="{0}.{1}".format(i, 0), text=subject_u,
values=sub_values[idx_1])
for idx_2, topic in enumerate(topicList[subject]):
topic_u = Input_Parser(topic, 'd2u')
tree.insert(Levels[subject], 'end', iid="{0}.{1}".format(i, j), text=topic_u,
values=top_values[subject][idx_2])
j += 1
i += 1
tree.bind("<Double-1>", lambda event: print(tree.identify_column(event.x)))
return tree, scrollbar
def treedelete(tree):
"""
Function to delete all treeview entries
:param tree: Tree in question
:return: None
"""
for i in tree.get_children():
tree.delete(i)
def repopulate(tree, version="full"):
"""
Repopulates the tree (using treedelete)
:param tree: Tree in question
:return: None
"""
treedelete(tree)
if version.lower() == 'full':
sub_values = []
top_values = {}
for i, subject in enumerate(subjectList):
sub_t_amount = len(topicList[subject])
sub_q_amount = 0
sub_q_done = 0
top_values[subject] = []
for topic in topicList[subject]:
df1, df2 = dataframe(KeyCodeTools().get_all_keycodes(topic))
count_failure, count_success, ratio = basic_stats(df1)
top_q_amount = KeyCodeTools().get_question_amount(topic)
top_q_done = count_failure + count_success
sub_q_amount += top_q_amount
sub_q_done += top_q_done
top_values[subject].append((' ', top_q_amount, top_q_done))
sub_values.append((sub_t_amount, sub_q_amount, sub_q_done))
namelst = ["Name", "# Topics", "# Questions", "# Questions Done"]
widthlst = [250, 150, 150, 200]
tree["columns"] = ["#{0}".format(i) for i in range(1, len(namelst))]
for i in range(len(tree["columns"])+1):
tree.column(f"#{i}", width=widthlst[i], minwidth=widthlst[i])
tree.heading(f"#{i}", text=namelst[i])
Levels = {}
i = 1
for idx_1, subject in enumerate(subjectList):
subject_u = Input_Parser(subject, 'd2u')
j = 1
Levels[subject] = tree.insert("", 'end', iid="{0}.{1}".format(i, 0), text=subject_u,
values=sub_values[idx_1])
for idx_2, topic in enumerate(topicList[subject]):
topic_u = Input_Parser(topic, 'd2u')
tree.insert(Levels[subject], 'end', iid="{0}.{1}".format(i, j), text=topic_u, values=top_values[subject][idx_2])
j += 1
i += 1
else:
sub_values = []
top_values = {}
for i, subject in enumerate(subjectList):
sub_q_done = 0
top_values[subject] = []
for topic in topicList[subject]:
df1, df2 = dataframe(KeyCodeTools().get_all_keycodes(topic))
count_failure, count_success, ratio = basic_stats(df1)
top_q_done = count_failure + count_success
sub_q_done += top_q_done
top_values[subject].append((top_q_done, 0))
sub_values.append((sub_q_done, 0))
namelst = ["Name", "# Questions Done", "Score"]
widthlst = [200, 110, 80]
tree["columns"] = ["#{0}".format(i) for i in range(1, len(namelst))]
for i in range(len(tree["columns"])+1):
tree.column(f"#{i}", width=widthlst[i], minwidth=widthlst[i])
tree.heading(f"#{i}", text=namelst[i])
Levels = {}
i = 1
for idx_1, subject in enumerate(subjectList):
subject_u = Input_Parser(subject, 'd2u')
j = 1
Levels[subject] = tree.insert("", 'end', iid="{0}.{1}".format(i, 0), text=subject_u,
values=sub_values[idx_1])
for idx_2, topic in enumerate(topicList[subject]):
topic_u = Input_Parser(topic, 'd2u')
tree.insert(Levels[subject], 'end', iid="{0}.{1}".format(i, j), text=topic_u,
values=top_values[subject][idx_2])
j += 1
i += 1
def AboutAcumen(frame):
"""
Upon clicking the button, another window will pop up,
showing version, credits, and other general information
"""
infoText = "Created by:\n " \
"Kevin Bislip\n " \
"Luke de Waal\n " \
"Victor Guillet\n " \
"and Xavier O'Rourke Goby\n" \
"\n" \
"Insipred by Maurício Aniche\n" \
"and Felienne Hermans"
infoWindow = tk.Toplevel(frame, bg="white")
infoWindow.resizable(False, False)
infoWindow.transient(frame)
infoWindow.title("About Acumen")
infoWindow.geometry("+500+500")
tk.Label(infoWindow, text="Version: 0.1", fg="black", bg="white").grid()
tk.Label(infoWindow, text=infoText, fg="black", bg="white").grid()
ttk.Button(infoWindow, text="Close", command=infoWindow.withdraw).grid()
def program_exit():
"""
Exits the program
"""
sys.exit()
def WarningWindow(frame, text1, text2="", exit=False):
warning = tk.Toplevel(frame, bg="white")
warning.resizable(False, False)
warning.transient(frame)
warning.title("Warning")
warning.geometry("+500+500")
lbFrame = tk.Frame(warning)
btFrame = tk.Frame(warning)
tk.Label(lbFrame, text=text1, fg="black", bg="white").grid(row=0, column=0)
if len(text2) != 0:
tk.Label(lbFrame, text=text2, fg="black", bg="white").grid(row=1, column=0, sticky=N+E+S+W)
if exit==False:
ttk.Button(btFrame, text="Close", command=warning.withdraw).grid(row=0, column=0)
elif exit==True:
ttk.Button(btFrame, text="Yes", command=program_exit).grid(row=0, column=0)
ttk.Button(btFrame, text="No", command=warning.withdraw).grid(row=0, column=1)
lbFrame.grid(row=0, column=0)
btFrame.grid(row=1, column=0)
def Update():
"""
Function used to update frames
:return: None
"""
App.after(1000, Update)
class AcumenApp(tk.Tk):
def __init__(self, *args, **kwargs):
"""
Initialization of base class, this is where all pages are managed
:param args: Tkinter-required args
:param kwargs: Tkinter-required kwargs
"""
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self, default='./GUI/icons/main_icon_2.ico')
tk.Tk.wm_title(self, "Acumen")
self.resizable(True, True)
self.width = 900
self.height = 620
self.xposition = int(self.winfo_screenwidth() / 2 - self.width / 2)
self.yposition = int(self.winfo_screenheight() / 2 - self.height / 2)
self.geometry("{0}x{1}+{2}+{3}".format(self.width, self.height, self.xposition, self.yposition))
container = tk.Frame(self)
container.grid(row=0, column=0)
dropdown = tk.Menu(container)
filemenu = tk.Menu(dropdown, tearoff=0)
filemenu.add_command(label="Settings", command=lambda: WarningWindow(container, "This Feature Has Not Been Implemented Yet", "Our Sincerest Apologies for this,\nIt will be implemented very soon"))
filemenu.add_command(label="Exit", command=lambda: WarningWindow(container, "Are you sure you wish to exit?", "Progress is saved automatically.", exit=True))
helpmenu = tk.Menu(dropdown, tearoff=0)
helpmenu.add_command(label="About Acumen", command=lambda: AboutAcumen(container))
dropdown.add_cascade(label="File", menu=filemenu)
dropdown.add_cascade(label="Help", menu=helpmenu)
tk.Tk.config(self, menu=dropdown)
self.frames = {}
self.FrameList = (StartPage, ClassesPage, ExamPage, StatsPage)
self.LabelList = ("Home Page", "Class Overview", "Exams", "Statistics")
for F in self.FrameList:
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='nsew')
self.switch_page(StartPage)
def switch_page(self, container):
"""
Function used to switch pages
:param container: frame in which to place new page
:return: None
"""
frame = self.frames[container]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
"""
Initialization of Start Page, this is the page that is shown first when started up
:param parent: parent frame
:param controller: tk.Tk controller
"""
NavButtons(self, parent, controller, text="Home Page")
welcomegrid = tk.Frame(self)
picturegrid = tk.Frame(self)
photo = Image.open('./GUI/icons/WelcomeImg.png')
photo = photo.resize((400, 325), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(photo)
lb = tk.Label(picturegrid, image=photo)
lb.image = photo
lb.grid(row=0, column=0)
photo = Image.open('./GUI/icons/maths_revision.png')
photo = photo.resize((400, 330), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(photo)
lb = tk.Label(picturegrid, image=photo)
lb.image = photo
lb.grid(row=1, column=0)
photo = Image.open('./GUI/icons/geography.png')
photo = photo.resize((460, 330), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(photo)
lb = tk.Label(welcomegrid, image=photo)
lb.image = photo
lb.grid(row=1, column=0)
text = tk.Text(welcomegrid, height=20, width=58)
scroll = tk.Scrollbar(welcomegrid, command=text.yview)
text.configure(yscrollcommand=scroll.set)
text.tag_configure('bold_italics', font=('Arial', 12, 'bold', 'italic'))
text.tag_configure('big', font=('Verdana', 20, 'bold'))
text.tag_configure('color', foreground='#476042',
font=('Tempus Sans ITC', 12, 'bold'))
text.tag_bind('follow', '<1>', lambda e, t=text: t.insert(END, "Not now, maybe later!"))
text.insert(END, '\n\tAcumen\n', 'big')
quote = "\n\n\tNoun\n" \
"\t'The ability to make good judgements \n\tand take quick decisions.'\n" \
"\tOrigin: Late 16th century: from Latin,\n\t‘sharpness, point’, from acuere ‘sharpen’." \
""
text.insert(END, quote, 'color')
text.config(state=DISABLED)
text.grid(row=0, column=0)
scroll.grid(row=0, column=1, sticky=N+S)
picturegrid.grid(row=2, column=0)
welcomegrid.grid(row=2, column=1)
# welcomegrid.grid_columnconfigure(0, weight=1)
# welcomegrid.grid_columnconfigure(1, weight=1)
# welcomegrid.grid_columnconfigure(2, weight=1)
# welcomegrid.grid_rowconfigure(0, weight=1)
class ClassesPage(tk.Frame):
def __init__(self, parent, controller):
"""
Class Page initialization
:param parent: parent frame
:param controller: tk.Tk controller
"""
NavButtons(self, parent, controller, text="Classes")
self.treeframe = tk.Frame(self, width=740, height=600)
self.tree, scrollbar = TreeView(self.treeframe)
btFrame = tk.Frame(self)
self.tree.bind("<<TreeviewSelect>>", lambda event: self.itemselection(event))
buttonsx, buttonsy = (10,10)
global item_selection
item_selection = []
global edit_selection
edit_selection = []
photo = Image.open('./GUI/icons/abstract/plus_green.png')
photo = photo.resize((40, 32), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(photo)
addsub_btn = ttk.Button(btFrame, text="Add", width=buttonsy, image=photo, compound=TOP,
command=self.AddWindow)
addsub_btn.image = photo
photo = Image.open('./GUI/icons/abstract/minus_red.png')
photo = photo.resize((40, 32), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(photo)
delsub_btn = ttk.Button(btFrame, text="Remove", width=buttonsy, image=photo, compound=TOP,
command=self.RemoveWindow)
delsub_btn.image = photo
photo = Image.open('./GUI/icons/office/pencil_green.png')
photo = photo.resize((40, 32), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(photo)
editsub_btn = ttk.Button(btFrame, text="Edit", width=buttonsy, image=photo, compound=TOP,
command=self.EditWindow)
editsub_btn.image = photo
photo = Image.open('./GUI/icons/actions/repeat_green.png')
photo = photo.resize((40, 32), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(photo)
refresh_btn = ttk.Button(btFrame, text="Refresh", width=buttonsy, image=photo, compound=TOP,
command= lambda: repopulate(self.tree))
refresh_btn.image = photo
addsub_btn.grid(row=0, column=1, sticky=N + W)
delsub_btn.grid(row=1, column=1, sticky=N + W)
editsub_btn.grid(row=2, column=1, sticky=N + W)
refresh_btn.grid(row=3, column=1, sticky=N + W)
btFrame.grid(row=2, column=2, sticky=N + W)
self.treeframe.pack_propagate(0)
self.tree.pack(side='left', fill="both")
scrollbar.pack(side='right')
self.treeframe.grid(row=2, column=0, sticky=N + E + W)
def itemselection(self, event):
"""
Function to return which items are selected in the treeview
:param event: <<TreeviewSelect>>
:return: None
"""
global item_selection
item_selection = self.tree.selection()
for select in item_selection:
if select[-1] == '0':
children = self.tree.get_children([select])
s = set(item_selection)
to_append = tuple([child for child in children if child not in s])
item_selection += to_append
#print(item_selection)
def EditWindow(self):
"""
Function creates a window where the user can edit names
:return: None
"""
self.editwindow = tk.Toplevel(self, bg='white')
self.editwindow.transient(self)
self.editwindow.title("Edit Names of Subjects and Topics")
global item_selection
selected = []
types = []
for item in item_selection:
if item[-1] != '0':
selected.append(KeyCodeTools().get_keycode_to_english_translation(item).split(".")[-1])
types.append(0)
elif item[-1] == '0':
selected.append(subjectList[int(item.split(".")[0])-1])
types.append(1)
headerFrame = tk.Frame(self.editwindow, bg='white')
entryFrame = tk.Frame(self.editwindow, bg='white')
btnFrame = tk.Frame(self.editwindow, bg='white')
entryVars = [tk.StringVar() for i in selected]
labels = [tk.Label(entryFrame, text=Input_Parser(selected[i], 'd2u')+":", bg='white') for i in range(len(selected))]
entries = [tk.Entry(entryFrame, textvariable=entryVars[i], bg='white') for i in range(len(selected))]
rows = 8
cols = int(len(selected)/rows)
rem = len(selected)%rows
if cols < 1:
cols = 1
rem = 0
rows = len(selected)
counter = 0
for i in np.arange(0, cols, 1)*2:
for j in range(rows):
labels[counter].grid(row=j, column=i, sticky=N+W)
entries[counter].grid(row=j, column=i+1, sticky=N+W)
counter+= 1
for r in range(rem):
labels[counter].grid(row=r, column=i+2, sticky=N+W)
entries[counter].grid(row=r, column=i+3, sticky=N+W)
counter += 1
headerLbl = tk.Label(headerFrame, text="Enter New Names and Press Confirm", font=Large_Bold_Font, bg='white')
emptyLbl_1 = tk.Label(headerFrame, text="\n", bg='white')
headerLbl.grid(row=0, column=0, sticky=N+W)
emptyLbl_1.grid(row=1, column=0)
cancelBtn = ttk.Button(btnFrame, text="Cancel", command=self.editwindow.withdraw)
confirmBtn = ttk.Button(btnFrame, text='Confirm', command=lambda: self.EditConfirm(entryVars, selected, types))
emptyLbl_2 = tk.Label(headerFrame, text="\n", bg='white')
emptyLbl_2.grid(row=0, column=0)
confirmBtn.grid(row=1, column=0)
cancelBtn.grid(row=1, column=1)
headerFrame.grid(row=0, column=0)
entryFrame.grid(row=1, column=0)
btnFrame.grid(row=2, column=0)
def EditConfirm(self, varlst, selectedlst, typelst):
"""
Once the user has put in all new names, this function can be called
:param varlst: List of stringvar variables
:param selectedlst: list of the selected items
:param typelst: list with 1's or 0's (1 for subjects, 0 for topics)
:return: None
"""
for idx, (var, select) in enumerate(zip(varlst, selectedlst)):
name = var.get()
type = typelst[idx]
if type == 0:
DBManager().edit_subject_or_topic_name_attribute(Input_Parser(name, 'u2d'), current_topic_name=Input_Parser(select, 'u2d'))
elif type == 1:
DBManager().edit_subject_or_topic_name_attribute(Input_Parser(name, 'u2d'), current_subject_name=Input_Parser(select, 'u2d'))
global subjectList, topicList
subjectList = DBManager().get_all_subjects_list()
topicList = DBManager().get_all_subject_topics_dict()
self.editwindow.withdraw()
def RemoveWindow(self):
"""
Window that is popped up to warn the user (s)he is about to delete the selected items
:return: None
"""
self.removewindow = tk.Toplevel(self, bg="white")
# self.addwindow.resizable(False, False)
self.removewindow.transient(self)
self.removewindow.title("Remove Topics and Subjects")
self.removewindow.geometry("+500+500")
global item_selection
btnFrame = tk.Frame(self.removewindow)
warninglabel = tk.Label(self.removewindow, text="Are you sure you wish to\ndelete these subjects/topics?", background='white')
confirmbtn = ttk.Button(btnFrame, text="Yes", command=lambda: self.removeconfirm(item_selection))
cancelbtn = ttk.Button(btnFrame, text="No", command=None)
cancelbtn.config(command=self.removewindow.withdraw)
warninglabel.grid(row=0, column=0)
confirmbtn.grid(row=0, column=0)
cancelbtn.grid(row=0, column=1)
btnFrame.grid(row=1, column=0)
def removeconfirm(self, selected):
"""
Function if user confirms (s)he wants to delete all selected items
:param selected: list of selected items
:return: none
"""
global subjectList, topicList
to_remove_subs = []
to_remove_topics = []
for selection in selected:
lst = selection.split(".")
subdigit = int(lst[0])
topdigit = int(lst[1])
if topdigit == 0:
to_remove_subs.append(subdigit)
elif topdigit != 0:
if subdigit in to_remove_subs:
continue
else:
to_remove_topics.append((subdigit, topdigit))
print(to_remove_subs)
if not len(to_remove_subs) == 0:
for sub in to_remove_subs:
DBManager().remove_subject_entirely_from_db(subjectList[sub-1])
if not len(to_remove_topics) == 0:
for sub, top in to_remove_topics:
topic = topicList[subjectList[sub-1]][top-1]
DBManager().remove_topic_entirely_from_db(topic)
subjectList = DBManager().get_all_subjects_list()
topicList = DBManager().get_all_subject_topics_dict()
repopulate(self.tree)
self.removewindow.withdraw()
def AddWindow(self):
"""
Window in which the user can add new subjects, topics or questions
:return: None
"""
self.addwindow = tk.Toplevel(self, bg="white")
#self.addwindow.resizable(False, False)
self.addwindow.transient(self)
self.addwindow.title("Add Topics and Subjects")
self.addwindow.geometry("+500+500")
self.dropdownvar = tk.StringVar()
self.dropdownvar.trace("r", self.main_comboboxselection)
dropdown = ttk.Combobox(self.addwindow, textvariable=self.dropdownvar)
dropdown['values'] = ['Subjects', 'Topics', 'Questions']
dropdown.bind("<<ComboboxSelected>>", self.main_comboboxselection)
dropdown.current(0)
lb1 = tk.Label(self.addwindow, text="Choose what you would like to add: ", bg="white")
lb1.grid(row=0, column=0, sticky=N+W+S)
dropdown.grid(row=0, column=1, sticky=N+W+S)
def main_comboboxselection(self, *args):
"""
Gets the users type input selection (Subject, Topic or Question)
:param args: Tkinter-required args
:return: None
"""
self.selected = self.dropdownvar.get()
for i in range(len(self.addwindow.winfo_children())):
widget = self.addwindow.winfo_children()[i]
if i in [0, 1]:
continue
else:
widget.grid_forget()
del self.addwindow.winfo_children()[i]
self.add_selection(self.addwindow, self.selected)
return
def integer_validate(self, var, old):
"""
Prevents wrong inputs from user when inputting an amount
:param var: variable linked to user input
:param old: standard value and/or old value
:return:
"""
new_value = var.get()
old_value = old
try:
new_value == '' or int(new_value)
old_value = new_value
except:
var.set(old_value)
def enterbutton_main(self, frame, btframe, type, *args):
"""
Enter Button command once the desired amount is given
:param frame: Topwindow frame
:param btframe: Frame containing Cancel and Enter buttons
:param type: Selection made in combobox
:param args: Amount or names
:return:
"""
if not type in ['Subjects', 'Topics', 'Questions']:
raise TypeError
if type == 'Subjects':
print(args)
val = int(args[0].get())
if val <= 0:
val = 1
variables = [tk.StringVar() for i in range(val)]
labels = [tk.Label(frame, text="Subject #{0}".format(i+1), bg='white') for i in range(val)]
entries = [ttk.Entry(frame, textvariable=variables[i]) for i in range(val)]
minrow = 3
btframe.grid(row=minrow+val)
self.en1.config(state=DISABLED)
self.bt1.config(command=lambda: self.sub_enterbutton(variables, self.checkvar))
for i in range(val):
labels[i].grid(row=minrow+i, column=0, sticky=N+W)
entries[i].grid(row=minrow+i, column=1, sticky=N+W)
elif type == 'Topics':
subject = args[0].get()
val = int(args[1].get())
if val <= 0:
val = 1
self.cb1.config(state=DISABLED)
self.en1.config(state=DISABLED)
variables = [tk.StringVar() for i in range(val)]
labels = [tk.Label(frame, text="Topic #{0}".format(i+1), bg='white') for i in range(val)]
entries = [ttk.Entry(frame, textvariable=variables[i]) for i in range(val)]
minrow = 4
btframe.grid(row=minrow + val)
self.bt1.config(command=lambda: self.top_enterbutton(variables, subject))
for i in range(val):
labels[i].grid(row=minrow + i, column=0, sticky=N + W)
entries[i].grid(row=minrow + i, column=1, sticky=N + W)
elif type == 'Questions':
subject = args[0].get()
topic = args[1].get()
val = int(args[2].get())
if val <= 0:
val = 1
elif val >= 20:
val = 20
self.cb1.config(state=DISABLED)
self.cb2.config(state=DISABLED)
self.en1.config(state=DISABLED)
minrow=5
qframe = tk.Frame(frame)
Qvariables = [tk.StringVar() for i in range(val)]
Qlabels = [tk.Label(qframe, text="Question #{0}".format(i+1), bg='white') for i in range(val)]
Qentries = [ttk.Entry(qframe, textvariable=Qvariables[i]) for i in range(val)]
Avariables = [tk.StringVar() for i in range(val)]
Alabels = [tk.Label(qframe, text="Answer #{0}".format(i+1), bg='white') for i in range(val)]
Aentries = [ttk.Entry(qframe, textvariable=Avariables[i]) for i in range(val)]
if val <= 10:
for i in range(val):
Qlabels[i].grid(row=i, column=0)
Qentries[i].grid(row=i, column=1)
Alabels[i].grid(row=i, column=2)
Aentries[i].grid(row=i, column=3)
elif val > 10:
mod10 = val%10
mod2 = mod10%2
if mod2 == 1:
len1 = round(val/2)
len2 = int(val/2)
for i in range(len1):
Qlabels[i].grid(row=i, column=0)
Qentries[i].grid(row= i, column=1)
Alabels[i].grid(row=i, column=2)
Aentries[i].grid(row=i, column=3)
i = 0
for j in range(len1, len1+len2):
Qlabels[j].grid(row=i, column=4)
Qentries[j].grid(row=i, column=5)
Alabels[j].grid(row=i, column=6)
Aentries[j].grid(row=i, column=7)
i += 1
elif mod2 == 0:
len1 = round(val/2)
len2 = int(val/2)
for i in range(len1):
Qlabels[i].grid(row=i, column=0)
Qentries[i].grid(row= i, column=1)
Alabels[i].grid(row=i, column=2)
Aentries[i].grid(row=i, column=3)
i = 0
for j in range(len1, len1+len2):
Qlabels[j].grid(row=i, column=4)
Qentries[j].grid(row=i, column=5)
Alabels[j].grid(row=i, column=6)
Aentries[j].grid(row=i, column=7)
i += 1
self.bt1.config(command=lambda: self.Q_enterbutton(Qvariables, Avariables, topic, subject))
emptylabel = tk.Label(btframe, bg='white')
emptylabel.grid(row=0, columnspan=3, sticky=N+S+E+W)
qframe.grid(row=minrow, columnspan=3)
btframe.grid(row=minrow + 1, sticky=N+W)
def add_selection(self, frame, selected):
"""
Once the type of new input is chosen (Sub, Top or Q) this function is fired and allows the user
to input the next details for the program to add
:param frame: Frame in which to add the new widgets
:param selected: Subject, Topic or Question
:return: None
"""