-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathexercise_4.py
112 lines (95 loc) · 3.16 KB
/
exercise_4.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
from gpa import Student
from graphics import *
from button import Button
def makeStudent(infoStr):
#inforStr is a tap-separated line: name hours getQPoints
#returns a corresponding Student object
name, hours, qpoints = infoStr.split("\t")
return Student(name, hours, qpoints)
def readStudents(filename):
infile = open(filename, 'r')
students = []
for line in infile:
students.append(makeStudent(line))
infile.close()
return students
def writeStudents(students, filename):
#students is a list of Student object
outfile = open(filename, 'w')
for s in students:
print("{0}\t{1}\t{2}".format(s.getName(), s.getHours(), s.getQPoints()), file = outfile)
outfile.close()
def sort(filename, x, m):
data = readStudents(filename)
while True:
if x == 'GPA':
data.sort(key=Student.gpa)
s = "_(GPA)"
if m == "D":
data.reverse()
break
elif x == 'name':
data.sort(key=Student.getName)
s = "_(name)"
if m == "D":
data.reverse()
break
elif x == 'credits':
data.sort(key=Student.getQPoints)
s = "_(credits)"
if m == "D":
data.reverse()
break
else:
print("Please try again.")
#filename = input("enter a name for the outputfile: ")
filename = "gpa" + s + ".txt"
return filename, data
def main():
#infile = input("Enter the name of the data file: ")
infile = 'gpa1.txt'
#Open Graphics Window
win = GraphWin("Arrange Student File", 800, 800)
win.setCoords(0, 0, 5, 6)
message = Text(Point(2.5,3), "This program sorts student grade information by GPA, name, or credits.\n Select the sorting method you would like.")
message.draw(win)
#Create Buttons for GPA, Name, and Credits
bSpecs = [(1,2,"GPA"), (2,2,"Name"), (3,2,"Credits"), (4,2,"Quit")]
buttons = []
for (cx, cy, label) in bSpecs:
buttons.append(Button(win, Point(cx,cy), .75, .75, label))
#....activate
for b in buttons:
b.activate()
while True:
click = win.getMouse()
#return clicked for each button
for b in buttons:
if b.clicked(click):
label = b.getLabel()
while label != "Quit":
if label == "GPA":
x = "GPA"
m = "D"
break
elif label == "Name":
x = "name"
m = "A"
break
elif label == "Credits":
x = "credits"
m = "D"
break
elif label == "Quit":
break
else:
message.setText("Please try again.")
click = win.getMouse()
#call sort function, which should return filename
outfile, data = sort(infile, x, m)
writeStudents(data, outfile)
outmessage = "The file has been printed to "+ outfile
message.setText(outmessage)
if label == "Quit":
break
if __name__ == '__main__': main()